C#中的通用inheritance类型限制
我有一个不太优雅的解决方案,我需要的,但我正在寻找一个优雅的解决方案来取代它。
以下代码无法编译,但代表了我想要做的事情:
interface IWebService { } abstract class BaseClient { } class SpecializedClient : BaseClient { } class ClientHelper where T : BaseClient { }
其中ClientHelper
中的ClientHelper
是任何扩展BaseClient
类,无论传入的模板类型如何。
我找到的不优雅的解决方案是:
class ClientHelper where T : BaseClient {}
这变得不优雅的原因是我的项目最终得到了类似于以下的类:
class MyClass where A : MyBaseClass
一直到一个类型的基类。 这只是具有generics类的复杂inheritance树的成本,还是有更简单的方法来保留模板化类型的类型限制?
如果BaseClient的公共接口以任何方式公开它的generics类型参数,那么你的“不优雅”解决方案是正确的。
所以假设BaseClient
不像你定义的那样:
abstract class BaseClient { //Something about T here }
然后T是BaseClient
的公共接口契约的BaseClient
,因此是ClientHelper
的公共接口契约的一部分(同样,假设BaseClient
通过ClientHelper的接口公开)。
另一方面,让我们假设它实际上就像你的例子所说:
abstract class BaseClient { //Nothing about T here }
在这种情况下,你可以这样做:
interface IBaseClient { //Nothing about T here } abstract class BaseClient : IBaseClient { // Whatever you like here }
和ClientHelper
成为:
class ClientHelper where T : IBaseClient { }
一种选择似乎是:
interface IWebService { } interface IClient { } abstract class BaseClient : IClient { } class SpecializedClient : BaseClient { } class ClientHelper where T : IClient
但是,只有当BaseClient
只返回T
并且从不接受它时, BaseClient
。