【发布时间】:2014-01-22 19:24:29
【问题描述】:
我正在尝试使用 Activator.CreateInstance 方法来动态创建一个新实例。但是,当我将可隐式转换为实际类型的类的实例(在构造函数中)传递时,我得到 System.MissingMethodException。 这是我用来验证的测试代码:
using System;
namespace ActivatorTest1
{
class Program
{
static void Main(string[] args)
{
Test t = new Test(new string[] { "abc" });
NewClass nc = new NewClass(new SubTest("apple"));
NewClass2 nc2 = nc;
try
{
Object[] paramList = new object[] { nc }; // nc is an instance of NewClass, which is implicitly castable to NewClass2
Activator.CreateInstance(typeof(Test), paramList);
Console.WriteLine("Instance successfully created");
Console.WriteLine("**************************");
}
catch (Exception exc)
{
Console.WriteLine("INSTANCE CREATION FAILED FOR IMPLICIT CASTING SCENARIO. \r\n\r\n " + exc);
}
Console.WriteLine("\r\n\r\n\r\n****************************************************\r\n\r\n\r\n");
try
{
Object[] paramList = new object[] { t }; // Although t is an instance of Test which is the base class for SubTest, MissingConstructorException is thrown
Activator.CreateInstance(typeof(NewClass), paramList);
Console.WriteLine("Instance successfully created");
Console.WriteLine("**************************");
}
catch (Exception exc)
{
Console.WriteLine("INSTANCE CREATION FAILED FOR DERIVED CLASS SCENARIO. \r\n " + exc);
}
Console.ReadKey();
}
}
class Test
{
public Test(string[] strArr)
{ }
public Test(NewClass2 nc2)
{ }
}
class SubTest : Test
{
public SubTest(string str)
: base(new string[] { str })
{ }
}
class NewClass // implicitly castable to NewClass2
{
public NewClass(SubTest st)
{ }
}
class NewClass2
{
public NewClass2()
{ }
public static implicit operator NewClass2(NewClass nc)
{
return new NewClass2();
}
}
}
当我传入派生类实例(也在上面的代码中)时,也会发生同样的事情。那么,这是预期的行为还是我在代码中做错了什么。对于这种情况,正确的出路是什么。谢谢。
编辑:关于第二部分,我的实现是错误的(如下面的答案中所述),一旦相应地修改了代码,就会成功地使用派生类作为参数创建所需的实例。 但是,关于隐式转换情况,仍然需要解决方法。也许一些与模式相关的解决方案,或者一些棘手/hacky 的实现,即使对于隐式可转换类型也会生成一个新实例?
【问题讨论】:
标签: .net oop reflection activator