在运行时执行隐式强制转换 [英] Execute implicit cast at runtime
问题描述
所以我有一个具有隐式强制转换的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 });
这篇关于在运行时执行隐式强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!