Pem*_*ing 6 .net c# reflection constructor implicit-conversion
我处于这样一种情况,我需要创建一个给定Type(作为字符串)的对象实例,以及一个构造函数参数数组.
这就是我实现的目标:
public object Create(string Name, params object[] Args)
{
return Activator.CreateInstance(Type.GetType(Name), Args);
}
Run Code Online (Sandbox Code Playgroud)
这在大多数情况下都可以正常工作,但是存在问题; 它不会将隐式转换考虑在内.
让我解释一下我的意思,说我们有一个简单的类,其中隐式转换为int定义
public class ImplicitTest
{
public double Val { get; set; }
public ImplicitTest(double Val)
{
this.Val = Val;
}
public static implicit operator int(ImplicitTest d)
{
return (int)d.Val;
}
}
Run Code Online (Sandbox Code Playgroud)
我们有一个使用int作为构造函数参数的类
public class TestClass
{
public int Val { get; set; }
public TestClass(int Val)
{
this.Val = Val;
}
}
Run Code Online (Sandbox Code Playgroud)
现在说我们想要创建一个TestClass实例,我们可以这样做:
new TestClass(5)
.在这种情况下,我们使用构造函数指定的确切参数类型(int).但是我们也可以使用ImplicitTest类创建类的实例,如下所示:new TestClass(new ImplicitTest(5.1))
.这是有效的,因为参数是从ImplicitTest隐式转换为int.然而,Activator.CreateInstance()不会这样做.
我们可以使用Create(string Name, params object[] Args)
之前的方法来创建TestClass的实例:Create("ThisNamespace.TestClass", 5)
这样可行.我遇到的问题是尝试使用隐式转换不起作用,因此此代码段会引发错误:Create("ThisNamespace.TestClass", new ImplicitTest(5.1))
我完全不知道如何考虑这一点,但这对我的用例很重要.也许我缺少Activator.CreateInstance()函数的一些参数,或者我可以使用一种完全不同的方法来实现我的目标?我找不到任何答案.
//Valid
new TestClass(5);
//Valid
new TestClass(new ImplicitTest(5.1));
//Valid
Activator.CreateInstance(Type.GetType("ThisNamespace.TestClass"), 5);
//Invalid, throws System.MissingMethodException
Activator.CreateInstance(Type.GetType("ThisNamespace.TestClass"), new ImplicitTest(5.1));
Run Code Online (Sandbox Code Playgroud)
为什么?