返回接口的通用方法

use*_*516 2 c#

我想编写一个返回 DAL 接口的通用方法,但它不起作用。

有可能做到这一点:

public MyInterface GetDAL()
{
   return new DAL(); // DAL implements MyInterface
}
Run Code Online (Sandbox Code Playgroud)

但不是这个:

public TInt GetDAL<TInt, TDAL>()
{
   return new TDAL();
}
Run Code Online (Sandbox Code Playgroud)

或这个

public TInt GetDAL<TInt, TDAL>()
{
   return (TInt)new TDAL();
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以返回具体的类而不是接口,但我不明白为什么它不起作用,如果 TDAL 实现了 TInt。

我有 10 个 DAL 类,我不想编写 10 个方法。

谢谢你的帮助

Ren*_*ogt 6

如果您告诉编译器以下的约束,它确实有效TDAL

public TInt GetDAL<TInt, TDAL>() where TDAL : TInt, new()
{
   return new TDAL();
}
Run Code Online (Sandbox Code Playgroud)

这告诉编译器TDAL必须实现TInt并具有无参数构造函数。
所以现在编译器知道TDAL表达式的任何类型参数new TDAL()都可以工作,并且结果可以赋值给TInt.