Dio*_*o F 23 .net c# reflection casting implicit-cast
我有一个Thing
可以从a中隐式转换的类string
.当我Thing
直接使用参数调用方法时,正确完成了string
to 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)
归档时间: |
|
查看次数: |
4202 次 |
最近记录: |