【发布时间】:2012-07-18 14:44:35
【问题描述】:
我有一个类Thing,它可以从string 隐式转换。当我直接调用带有Thing 参数的方法时,从string 到Thing 的转换正确完成。
但是,如果我使用反射来调用相同的方法,它会引发异常
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