fl4*_*n4g 1 c# generics methods
我想创建简单的工厂类,实现这样的接口:
IFactory
{
TEntity CreateEmpty<TEntity>();
}
Run Code Online (Sandbox Code Playgroud)
在这个方法中,我想返回一个TEntity类型的实例(泛型类型).例:
TestClass test = new Factory().CreateEmpty<TestClass>();
Run Code Online (Sandbox Code Playgroud)
可能吗?界面是否正确?
我尝试过这样的事情:
private TEntity CreateEmpty<TEntity>() {
var type = typeof(TEntity);
if(type.Name =="TestClass") {
return new TestClass();
}
else {
...
}
}
Run Code Online (Sandbox Code Playgroud)
但它没有编译.
您需要new()在泛型类型参数上指定约束
public TEntity CreateEmpty<TEntity>()
where TEntity : new()
{
return new TEntity();
}
Run Code Online (Sandbox Code Playgroud)
新约束指定所使用的具体类型必须具有公共默认构造函数,即不带参数的构造函数.
public TestClass
{
public TestClass ()
{
}
...
}
Run Code Online (Sandbox Code Playgroud)
如果您根本没有指定任何构造函数,则默认情况下该类将具有公共默认构造函数.
您无法在new()约束中声明参数.如果需要传递参数,则必须为此目的声明专用方法,例如通过定义适当的接口
public interface IInitializeWithInt
{
void Initialize(int i);
}
public TestClass : IInitializeWithInt
{
private int _i;
public void Initialize(int i)
{
_i = i;
}
...
}
Run Code Online (Sandbox Code Playgroud)
在你的工厂里
public TEntity CreateEmpty<TEntity>()
where TEntity : IInitializeWithInt, new()
{
TEntity obj = new TEntity();
obj.Initialize(1);
return obj;
}
Run Code Online (Sandbox Code Playgroud)