我有一个工厂,它应该在运行时创建从类 Foo 继承的对象。我本以为System.Activator.CreateInstance的返回类型与其创建的对象类型相同,但从下面的错误信息来看,它的返回类型是Object。
Error 1 Cannot implicitly convert type 'object' to 'cs_sandbox.Foo'. An explicit conversion exists (are you missing a cast?) F:\projects\cs_sandbox\Form1.cs 46 24 cs_sandbox
好吧,也许我错过了类型转换,但是
return (t)System.Activator.CreateInstance(t);
导致又一条错误消息,我必须承认,这对我来说毫无意义:
Error 1 The type or namespace name 't' could not be found (are you missing a using directive or an assembly reference?) F:\projects\cs_sandbox\Form1.cs 45 25 cs_sandbox
这是我的代码:
class Foo { }
class FooChild1 : Foo { }
class FooChild2 : Foo { }
class MyFactory
{
public static Foo CreateInstance(string s)
{
Type t;
if (s.StartsWith("abcdef"))
{
t = typeof(FooChild1);
return System.Activator.CreateInstance(t);
}
else
{
t = typeof(FooChild2);
return System.Activator.CreateInstance(t);
}
}
}
如何修复此代码?或者,如果无法修复,还有哪些其他方法可以在运行时创建从特定类继承的对象?
最佳答案
您需要将返回的对象转换为 Foo
类型。将其转换为变量中定义的类型没有意义。编译器应该知道这一点,因为通过继承层次结构进行强制转换的全部意义在于满足编译器的静态类型检查。
return (Foo)System.Activator.CreateInstance(t);
有一个通用版本,System.Activator.CreateInstance<T>
,它创建一个已知类型(不是类型变量而是类型参数或静态已知类型,在后一种情况下,它没有多大意义):
return System.Activator.CreateInstance<FooChild1>();
关于c# - Activator.CreateInstance() 的麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1484577/