【问题标题】:Both a generic constraint and inheritance通用约束和继承
【发布时间】:2014-04-08 14:33:10
【问题描述】:

我有这种情况:

class A<T> 

我想要一个 Person 类型的约束,比如

class A<T> where T: Person

我也希望 A 从 B 继承。

示例:

class A<T> : B : where T: Person

class A<T> where T: Person,  B

我该怎么做?

【问题讨论】:

  • 我希望我的编辑是正确的,但是您的原始标题让我感到奇怪。看起来您不是想要“或”,而是想要继承和约束。

标签: c# generics inheritance


【解决方案1】:
class A<T> : B where T : Person

【讨论】:

    【解决方案2】:

    您不能从 C# 中的 多个 类继承。所以你可以拥有

    A&lt;T&gt; 继承自 BTPersonPersonclassinterface):

    class A<T>: B where T: Person {
      ...
    }
    

    A&lt;T&gt; 不需要继承自B;但T 继承自B 并实现PersonPerson 只能是接口):

    class A<T> where T: Person, B {
      ...
    }
    

    看来你想要案例1:

    // A<T> inherites from B; 
    // T is restricted as being Person (Person is a class or interface)
    class A<T>: B where T: Person {
      ...
    }
    

    【讨论】:

    • 我不是指多重继承,只是泛型类型的约束,并且....从其他类继承
    【解决方案3】:

    您是在问如何在 C# 中表达这种结构?如果是这样,下面一个例子:

    class Program
    {
        static void Main(string[] args)
        {
            B a1 = new A<Person>();
            B a2 = new A<ChildPerson>();
        }
    }
    class Person
    {
    }
    
    class ChildPerson : Person
    {
    }
    
    class A<T> : B where T: Person
    {
    }
    
    class B
    {
    }
    

    【讨论】:

    • 很好的例子,包括用于说明的ChildPerson 类。也许只是为了清楚起见,添加一个注释,您只添加了该类以进行说明;请求的功能不需要它?
    【解决方案4】:

    C# 中没有多重继承,因此不能强制一个类型从多个类继承。

    听起来你的结构不正确。

    为了确保两者都实现,其中一个必须是接口,或者其中一个必须实现另一个。

    如果你的意思是 T 可以实现 B 或 Person,那么应该有一些 B 和 Person 共享的抽象基类/接口,你可以限制它

    【讨论】:

    • 我不是指多重继承,只是对泛型类型的约束,并且....从其他类继承
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多