【问题标题】:How to cast implicitly on a reflected method call如何在反射方法调用上隐式转换
【发布时间】:2012-07-18 14:44:35
【问题描述】:

我有一个类Thing,它可以从string 隐式转换。当我直接调用带有Thing 参数的方法时,从stringThing 的转换正确完成。

但是,如果我使用反射来调用相同的方法,它会引发异常

System.ArgumentException : Object of type 'System.String' cannot be 
converted to type 'Things.Program+Thing'.

也许有一个很好的理由,但我想不通。有人知道如何使用反射来完成这项工作吗?

namespace Things
{
    class Program
    {
        public class Thing
        {
            public string Some;

            public static implicit operator Thing(string s)
            {
                return new Thing {Some = s};
            }
        }

        public void showThing(Thing t)
        {
            Console.WriteLine("Some = " + t.Some);
        }

        public void Main()
        {
            showThing("foo");
            MethodInfo showThingReflected = GetType().GetMethod("showThing");
            showThingReflected.Invoke(this, new dynamic[] {"foo"});
        }
    }
}

Meta:请不要讨论为什么隐式转换或反射不好。

【问题讨论】:

  • 在我的脑海中,我敢打赌这是因为(我认为,如果我错了,请纠正我)隐式转换对于编译器来说是语法糖。对转换方法的实际调用是在编译时连接的。编辑:您是否需要一些通用的方法来调用任何对象转换的隐式转换器?或者这是一种特殊情况,您愿意将单独的静态方法或其他反射调用作为预定方法或专门的构造函数的目标?
  • 类似问题here
  • 无法通过反射进行隐式转换,但您可以使用TypeConvertor
  • 如果你真的想这样做,你可以构造一个表达式树来满足你的需要,然后将它编译成一个方法并执行它。如果您觉得这对您有用,我可以将其添加为答案。
  • @ChrisSinclair:实际上我使用了第三方应用程序来执行反射。但我想我可以以某种方式包装它。

标签: c# .net reflection casting implicit-conversion


【解决方案1】:

诀窍是要意识到编译器会为您的隐式转换运算符创建一个名为 op_Implicit 的特殊静态方法。

object arg = "foo";

// Program.showThing(Thing t)
var showThingReflected = GetType().GetMethod("showThing");

// typeof(Thing)
var paramType = showThingReflected.GetParameters()
                                  .Single()
                                  .ParameterType; 

// Thing.implicit operator Thing(string s)
var converter = paramType.GetMethod("op_Implicit", new[] { arg.GetType() });

if (converter != null)
    arg = converter.Invoke(null, new[] { arg }); // Converter exists: arg = (Thing)"foo";

// showThing(arg)
showThingReflected.Invoke(this, new[] { arg });

【讨论】:

【解决方案2】:

找到了一个使用 TypeConverter 的答案(正如 Saeed 提到的)
似乎可以胜任。

TypeConverter For Implicit Conversion when using reflection

【讨论】:

    【解决方案3】:

    在这种特定情况下,您可以通过数组类型进行转换,即

    showThingReflected.Invoke(this, new Thing[] {"foo"});
    

    但这是一种“作弊”。通常,您不能指望Invoke 考虑您的用户定义的implicit operator。这种转换必须在编译时推断。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      • 2010-12-09
      • 1970-01-01
      • 2022-12-31
      • 2014-05-20
      相关资源
      最近更新 更多