[英]How to create generic method which return instance of generic?
我想創建實現如下接口的簡單工廠類:
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 {
...
}
}
但是它不能編譯。
您需要在通用類型參數上指定new()
約束
public TEntity CreateEmpty<TEntity>()
where TEntity : new()
{
return new TEntity();
}
新的約束指定所使用的具體類型必須具有公共默認構造函數,即沒有參數的構造函數。
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;
}
interface IFactory<TEntity> where T : new()
{
TEntity CreateEmpty<TEntity>();
}
此方法將幫助您按順序在構造函數中傳遞參數:
private T CreateInstance<T>(params object[] parameters)
{
var type = typeof(T);
return (T)Activator.CreateInstance(type, parameters);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.