2012-03-09 74 views
3
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有一个公共的默认构造函数,我希望客户端不必指定如何构造一个(通过第一个构造函数)。不过,我想允许Product没有公共默认构造函数(通过第二个构造函数)的情况。带有“条件”约束的C#泛型类?

Factory的通用约束是允许实现第一个构造函数所必需的,但它禁止在没有公共默认构造函数的情况下使用任何类。

有没有办法让两者兼容?

回答

8

不是直接的,但你可以使用非通用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; 
}