在运行时执行隐式强制转换

编程入门 行业动态 更新时间:2024-10-25 12:28:45
本文介绍了在运行时执行隐式强制转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以我有一个具有隐式强制转换的Generic类(主要是容器类),如下所示:

So I have a Generic class (it's mostly a container class) with implicit casting, like this:

public class Container<T> { public T Value { get; set; } public static implicit operator T(Container<T> t) { return t.Value; } public static implicit operator Container<T>(T t) { return new Container<T>() { Value = t }; } }

因此,在运行时中,我想使用反射将 Container< int> 的实例转换为int,但似乎找不到方法,我尝试了几个地方,但我得到一个指定的强制转换无效.异常.

So in runtime I would like to cast an instance of Container<int> to int using reflection but cannot seem to find a way, I've tried the "Cast" method invoking mentioned in a couple of places but I'm getting an Specified cast is not valid. exception.

任何帮助将不胜感激.

推荐答案

除非有待讨论的类型是无法修改的程序集的内部类型,否则几乎没有很好的理由.

There's almost never a good reason to do this unless the type in question is internal to an assembly that you cannot modify.

但是,涉及到这一点,我个人更喜欢外观更简洁的 dynamic 解决方案(如jbtule所述)而不是反射.

But if it came to that, I would personally prefer the much cleaner-looking dynamic solution (as mentioned by jbtule) to reflection.

但是由于您要求使用反射解决方案(也许您使用的是.NET 3.5或更早的版本?),所以可以这样做:

But since you asked for a solution with reflection (perhaps you are on .NET 3.5 or earlier?), you can do:

object obj = new Container<int>(); var type = obj.GetType(); var conversionMethod = type.GetMethod("op_Implicit", new[] { type }); int value = (int)conversionMethod.Invoke(null, new[] { obj });

更多推荐

在运行时执行隐式强制转换

本文发布于:2023-11-10 22:48:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1576675.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:隐式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!