简体   繁体   English

返回接口的通用方法

[英]Generic method which return Interface

I would like to write a generic method that return DAL interfaces but it doesn't works.我想编写一个返回 DAL 接口的通用方法,但它不起作用。

It's possible to make this :有可能做到这一点:

public MyInterface GetDAL()
{
   return new DAL(); // DAL implements MyInterface
}

But not this :但不是这个:

public TInt GetDAL<TInt, TDAL>()
{
   return new TDAL();
}

or this或这个

public TInt GetDAL<TInt, TDAL>()
{
   return (TInt)new TDAL();
}

I know I could return concrete class instead of interface but I don't understand why it doens't works, if TDAL implements TInt.我知道我可以返回具体的类而不是接口,但我不明白为什么它不起作用,如果 TDAL 实现了 TInt。

I have 10 DAL classes and I don't want to write 10 methods.我有 10 个 DAL 类,我不想编写 10 个方法。

Thanks for your help谢谢你的帮助

It does work if you tell the compiler the constraints for TDAL :如果您告诉编译器TDAL约束,它确实有效:

public TInt GetDAL<TInt, TDAL>() where TDAL : TInt, new()
{
   return new TDAL();
}

This tells the compiler that TDAL must implement TInt and have a parameterless constructor.这告诉编译器TDAL必须实现TInt ,并有参数的构造函数。
So now the compiler knows that for any type argument for TDAL the expression new TDAL() will work and that the result is assignable to TInt .所以现在编译器知道对于TDAL的任何类型参数,表达式new TDAL()都可以工作,并且结果可以分配给TInt

new TDAL() won't work because not all classes have a parameterless constructor, or inherit from TInt . new TDAL()将不起作用,因为并非所有类都有无参数构造函数,或者从TInt继承。

You need to add type constraints to your method eg您需要为您的方法添加类型约束,例如

public TInt GetDAL<TInt, TDAL>() where TDAL : new(), TInt
{
   return new TDAL();
}

Then when you use your method, the compiler will enforce a compatible type to be used.然后,当您使用您的方法时,编译器将强制使用兼容类型。

MyInterface dal = GetDAL<MyInterface, DAL>(); // Will compile

MyInterface dal = GetDAL<TMyInterface, string>(); // Won't compile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM