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;
}
Run Code Online (Sandbox Code Playgroud)
在Factory
,当Product
有一个公共默认构造函数时,我希望客户端不必指定如何构造一个(通过第一个构造函数).但是,我想允许Product
没有公共默认构造函数的情况(通过第二个构造函数).
Factory
需要通用约束来允许第一个构造函数的实现,但它禁止在没有公共默认构造函数的情况下使用任何类.
有没有办法允许两者?
不是直接的,但你可以使用非通用Factory
工厂(原文如此)与通用方法,把类型约束上的类型参数的方法,并用它来委托提供给不受约束Factory<T>
类.
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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
731 次 |
最近记录: |