如何隐式地反射方法调用

Dio*_*o F 23 .net c# reflection casting implicit-cast

我有一个Thing可以从a中隐式转换的类string.当我Thing直接使用参数调用方法时,正确完成了stringto Thing的强制转换.

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

System.ArgumentException : Object of type 'System.String' cannot be 
converted to type 'Things.Program+Thing'.
Run Code Online (Sandbox Code Playgroud)

也许有充分的理由,但我无法弄明白.有人知道如何使用反射工作吗?

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"});
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Meta:请不要讨论为什么隐式投射或反射是坏的.

Ani*_*Ani 12

诀窍是要意识到编译器会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 });
Run Code Online (Sandbox Code Playgroud)


Ala*_*anT 5

找到了一个使用 TypeConverter 的答案(如 Saeed 提到的)
似乎可以完成这项工作。

TypeConverter 用于使用反射时的隐式转换