【问题标题】:Execute implicit cast at runtime在运行时执行隐式转换
【发布时间】: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&lt;int&gt; 的实例转换为 int 但似乎找不到方法,我尝试了几个地方提到的“Cast”方法调用但我得到了Specified cast is not valid. 异常。

任何帮助将不胜感激。

【问题讨论】:

  • 那么你在编译时知道什么,在执行时你知道什么?可以给我们调用代码吗?
  • 您是在尝试将 Container 转换为 int 还是 Container.Value?
  • 你为什么不直接打电话给Container.Value
  • 我不一定知道泛型变量的实例具有“值”属性,这只是一个简化的示例,本质上我想(尝试)将容器变量转换为它包含,例如将Tuple&lt;int&gt; 转换为int,假设Tuple&lt;int&gt; 实际上对其包含的类型进行了隐式转换,或者像我的容器一样,将Container&lt;Customer&gt; 转换为Customer

标签: c# generics reflection


【解决方案1】:

除非所讨论的类型是您无法修改的程序集的内部类型,否则几乎没有充分的理由这样做。

但如果是这样的话,我个人更喜欢看起来更干净的dynamic 解决方案(如 jbtule 所述)而不是反射。

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

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 });

【讨论】:

    【解决方案2】:

    通过使用 dlr,可通过 nuget 中的开源 ImpromptuInterface 访问,您可以动态地 call an implicit or explicit cast

    int intInstance =Impromptu.InvokeConvert(containerInstance, typeof(int));
    

    虽然这个例子比较简单,可以通过

    int intInstance = (dynamic) containerInstnace;
    

    也是。但如果你在编译时不知道int,即兴表演是最好的选择。

    【讨论】:

      【解决方案3】:

      编写隐式运算符允许您隐式地进行强制转换。换句话说,这是完全合法的:

      int i = new Container<int>() { Value = 2 };
      if (i == 2) 
      {
          // This will be executed
      }
      

      如果您只有一个Container&lt;object&gt;,那么这将不起作用,但在这种情况下,您的代码可能无论如何都应该重构,因为您实际上忽略了您拥有的通用参数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-22
        • 1970-01-01
        相关资源
        最近更新 更多