在C#泛型继承类型限制 [英] Generic inherited type restriction in C#

查看:116
本文介绍了在C#泛型继承类型限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有什么,我需要一个不雅的解决方案,但要寻找一个优雅的解决方案来取代它。

I have an inelegant solution for what I need, but am looking for an elegant solution to replace it.

下面的代码无法编译,而是代表着什么我想这样做:

The following code doesn't compile, but represents what I would like to do:

interface IWebService
{
}

abstract class BaseClient<T>
{
}

class SpecializedClient : BaseClient<IWebService>
{
}

class ClientHelper<T> where T : BaseClient<*>
{
}



T ClientHelper< T> 是扩展不管模板类型中通过了 BaseClient 的任何类。

Where the T in ClientHelper<T> is any class that extends BaseClient regardless of the templated type passed in.

该不雅的解决方案,我发现的是:

The inelegant solution I found is:

class ClientHelper<T, U> where T : BaseClient<U> {}

这成为不雅的原因是我的项目,类似于类结束:

The reason this becomes inelegant is my project ends up with a class similar to:

class MyClass<A, B, C, D, E, F, G> where A  : MyBaseClass<B, C, D, E, F, G>



一路下来基类,它接受一个单一类型。这是只要有泛型类的复杂继承树的成本或者是有一个简单的方法来做到这一点,而在模板类型固定类型的限制?

All the way down to the base class that takes a single type. Is this simply the cost of having a complex inheritance tree of generic classes or is there a simpler way to do this while retaining type restrictions on the templated types?

推荐答案

您不雅的解决办法是,如果BaseClient的公共接口公开它在任何泛型类型参数是正确的。

Your "inelegant" solution is the right one if the public interface of BaseClient exposes it's generic type parameter in any way.

所以假设 BaseClient 不会当你定义它:

So assuming BaseClient is not as you defined it:

abstract class BaseClient<T>
{
   //Something about T here
}

然后T是 BaseClient 的公共接口契约的一部分,因此, ClientHelper 的公共接口契约的一部分(再次,假设 BaseClient< U> 通过ClientHelper接口暴露)

Then T is part of the public interface contract of BaseClient, and therefore part of the public interface contract of ClientHelper (again, assuming that BaseClient<U> is exposed via the interface of ClientHelper).

在另一方面,我们假设它实际上是你的榜样所说的:

On the other hand, let's assume it actually is as your example puts it:

abstract class BaseClient<T>
{
   //Nothing about T here
}

在这种情况下,你可以这样做:

In that case, you can do:

interface IBaseClient
{
   //Nothing about T here
}

abstract class BaseClient<T> : IBaseClient
{ 
    // Whatever you like here
}

ClientHelper 变为:

class ClientHelper<T> where T : IBaseClient
{
}

这篇关于在C#泛型继承类型限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆