2012-03-09 77 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; 
}