简体   繁体   English

为什么实现具有类型约束的通用接口的泛型类需要重复这些约束?

[英]Why does a generic class implementing a generic interface with type constraints need to repeat these constraints?

Let's say I have a following C# interface: 假设我有一个以下的C#界面:

public interface IInterface<T> where T : SomeClass
{
    void InterfaceMethod();
}

And SomeClass is defined as follows: 而SomeClass的定义如下:

public class SomeClass
{
    public void SomeMethod();
}

Now I'd like to define the implementation of the interface, which won't compile: 现在我想定义接口的实现,它不会编译:

public class InterfaceImpl<T> : IInterface<T> 
{
    public void InterfaceMethod()
    {
        T test = default(T);
        test.SomeMethod(); //Gives Error
    }
}

before I change it to: 在我改为之前:

public class InterfaceImpl<T> : IInterface<T> where T : SomeClass
{
    public void InterfaceMethod()
    {
        T test = default(T);
        test.SomeMethod(); //Compiles fine
    }
}

Wouldn't it make sense that the type constraints are also "inherited" (not the right word, I know) from the interface? 从界面中类型约束是否也“继承”(不是正确的词,我知道)是否有意义?

The class does not need to repeat these constraints, it needs to supply a type that satisfies the constraints of the interface. 该类不需要重复这些约束,它需要提供满足接口约束的类型。 There are several ways of doing it: 有几种方法可以做到:

  • It can supply a specific type that satisfies the constraints, or 它可以提供满足约束的特定类型,或
  • It can place its own constraints on a generic type that are stronger than what the interface expects, or 它可以将自己的约束放在比接口期望的更强的泛型类型上,或者
  • It can repeat the constraints from the interface. 它可以重复界面的约束。

The key thing is that T in InterfaceImpl<T> belongs to InterfaceImpl , so whatever constraints that are placed on T must be InterfaceImpl 's own. 关键的是, TInterfaceImpl<T>属于InterfaceImpl ,以便被放置在任何约束T必须InterfaceImpl自身。

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

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