Dav*_*ale 3 c# generics factory-pattern object-construction
是否可以在通用方法中使用其内部构造函数构造对象?
public abstract class FooBase { }
public class Foo : FooBase {
internal Foo() { }
}
public static class FooFactory {
public static TFooResult CreateFoo<TFooResult>()
where TFooResult : FooBase, new() {
return new TFooResult();
}
}
Run Code Online (Sandbox Code Playgroud)
FooFactory与驻留在同一程序集中Foo。类调用工厂方法,如下所示:
var foo = FooFactory.CreateFoo<Foo>();
Run Code Online (Sandbox Code Playgroud)
他们得到编译时错误:
“ Foo”必须是具有公共无参数构造函数的非抽象类型,才能在通用类型或方法“ FooFactory.CreateFoo()”中用作参数“ TFooType”
有什么办法可以解决这个问题?
我也尝试过:
Activator.CreateInstance<TFooResult>();
Run Code Online (Sandbox Code Playgroud)
这会在运行时引发相同的错误。
您可以删除new()约束并返回:
//uses overload with non-public set to true
(TFooResult) Activator.CreateInstance(typeof(TFooResult), true);
Run Code Online (Sandbox Code Playgroud)
尽管客户也可以这样做。但是,这容易导致运行时错误。
由于该语言不允许抽象构造函数声明,因此很难以安全的方式解决该问题。