class Factory<Product> where Product : new()
{
public Factory()
: this(() => new Product())
{
}
public Factory(System.Func<Product> build)
{
this.build = build;
}
public Product Build()
{
return build();
}
private System.Func<Product> build;
}
在 Factory
中,当 Product
有一个公共(public)默认构造函数时,我希望客户不必指定如何构造一个(通过第一个构造函数)。但是,我想允许 Product
没有公共(public)默认构造函数(通过第二个构造函数)的情况。
Factory
的泛型约束是允许第一个构造函数的实现所必需的,但它禁止在没有公共(public)默认构造函数的情况下与任何类一起使用。
有没有办法同时允许两者?
最佳答案
不是直接的,但您可以使用非通用的 Factory
具有泛型方法的工厂(原文如此),将类型约束放在方法的类型参数上,并使用它来向不受约束的 Factory<T>
提供委托(delegate)类。
static class Factory
{
public static Factory<T> FromConstructor<T>() where T : new()
{
return new Factory<T>(() => new T());
}
}
class Factory<TProduct>
{
public Factory(Func<TProduct> build)
{
this.build = build;
}
public TProduct Build()
{
return build();
}
private Func<TProduct> build;
}
关于具有 "conditional"约束的 C# 泛型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9636934/