[英]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: 有几种方法可以做到:
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. 关键的是, T
在InterfaceImpl<T>
属于InterfaceImpl
,以便被放置在任何约束T
必须InterfaceImpl
自身。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.