2012-05-05 153 views
0

我要創建簡單的工廠類,它實現接口這樣的:如何創建返回泛型實例的泛型方法?

IFactory 
{ 
    TEntity CreateEmpty<TEntity>(); 
} 

在這種方法我想返回類型TEntity(通用型)的實例。 例如:

TestClass test = new Factory().CreateEmpty<TestClass>(); 

這可能嗎?界面是否正確?

我已經試過這樣的事情:

private TEntity CreateEmpty<TEntity>() { 
    var type = typeof(TEntity); 
    if(type.Name =="TestClass") { 
     return new TestClass(); 
    } 
    else { 
    ... 
    } 
} 

不過,這並不編譯。

回答

6

你需要指定的泛型類型參數

public TEntity CreateEmpty<TEntity>() 
    where TEntity : new() 
{ 
    return new TEntity(); 
} 

新的限制規定的約束new()所使用必須有一個公共的默認構造函數的具體類型,即無參數的構造函數。

public TestClass 
{ 
    public TestClass() 
    { 
    } 

    ... 
} 

如果您根本不指定任何構造函數,那麼默認情況下該類將具有公共的默認構造函數。

你不能聲明在new()約束參數。如果您需要傳遞參數,則必須爲此目的聲明專用方法,例如通過定義一個適當的接口

public interface IInitializeWithInt 
{ 
    void Initialize(int i); 
} 

public TestClass : IInitializeWithInt 
{ 
    private int _i; 

    public void Initialize(int i) 
    { 
     _i = i; 
    } 

    ... 
} 

在你的工廠

public TEntity CreateEmpty<TEntity>() 
    where TEntity : IInitializeWithInt, new() 
{ 
    TEntity obj = new TEntity(); 
    obj.Initialize(1); 
    return obj; 
} 
+0

謝謝爲全面解答。 – fl4izdn4g

2
interface IFactory<TEntity> where T : new() 
{ 
    TEntity CreateEmpty<TEntity>(); 
} 
2

這種方法會幫助你的,因爲爲了傳遞參數,它們在構造函數:

private T CreateInstance<T>(params object[] parameters) 
{ 
    var type = typeof(T); 

    return (T)Activator.CreateInstance(type, parameters); 
}