如何隐式地reflection方法调用
我有一个可以从string
隐式转换的类Thing
。 当我直接使用Thing
参数调用方法时,从string
到Thing
的强制转换正确完成。
但是,如果我使用reflection调用相同的方法,它会抛出exception
System.ArgumentException : Object of type 'System.String' cannot be converted to type 'Things.Program+Thing'.
也许有充分的理由,但我无法弄明白。 有人知道如何使用reflection工作吗?
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: 请不要讨论为什么隐式转换或reflection是坏的。
找到一个使用TypeConverter的答案(如Saeed提到的)
似乎做了这个工作。
TypeConverter用于使用reflection时的隐式转换
诀窍是要意识到编译器为隐式转换运算符创建了一个名为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 });
在这种特定情况下,您可以通过数组类型进行转换,即
showThingReflected.Invoke(this, new Thing[] {"foo"});
但那是一种“作弊”。 通常,您不能指望Invoke
考虑用户定义的implicit operator
。 必须在编译时推断此转换。