【发布时间】:2011-08-15 13:24:36
【问题描述】:
所以我有一个带有隐式转换的通用类(它主要是一个容器类),如下所示:
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 但似乎找不到方法,我尝试了几个地方提到的“Cast”方法调用但我得到了Specified cast is not valid. 异常。
任何帮助将不胜感激。
【问题讨论】:
-
那么你在编译时知道什么,在执行时你知道什么?可以给我们调用代码吗?
-
您是在尝试将 Container 转换为 int 还是 Container.Value?
-
你为什么不直接打电话给
Container.Value? -
我不一定知道泛型变量的实例具有“值”属性,这只是一个简化的示例,本质上我想(尝试)将容器变量转换为它包含,例如将
Tuple<int>转换为int,假设Tuple<int>实际上对其包含的类型进行了隐式转换,或者像我的容器一样,将Container<Customer>转换为Customer。
标签: c# generics reflection