简体   繁体   English

在泛型约束中使用类型

[英]Using type in generic constraint

I'm studying with C# in depth book and it mentions that a form of constraint uses the type parameter in the constraint itself.我正在使用 C# 深入学习这本书,它提到一种约束形式在约束本身中使用类型参数。 So what is the difference between these two:那么这两者有什么区别:

public void Method(AClass<T> myobject) where T : ISomething //Here I say that T has to implement ISomething

public void Method(AClass<T> myobject) where T : ISomething<T> //I don't understand this

Consider that you have a non-generic interface ISomething defined.考虑您定义了一个非通用接口ISomething The first line constrains T to types that implement that interface.第一行将T限制为实现该接口的类型。

Now consider that you have a different, generic interface ISomething<T> defined.现在考虑您定义了一个不同的通用接口ISomething<T> The second line says that T is constrained to types that implement that interface, but with the further restriction that the generic parameter on the interface must the set to the type that you are specifying.第二行表示 T 被约束为实现该接口的类型,但进一步的限制是接口上的泛型参数必须设置为您指定的类型。

For example例如

interface ISomething<T> { /* methods */}

class MyClass: ISomething<MyClass> { /* methods */ }

See the relationship that MyClass has with ISomething<T> .查看MyClassISomething<T> That's what that constraint is demanding.这就是约束所要求的。

C++ programmers call this the Curiously Recurring Template Pattern ( https://en.m.wikipedia.org/wiki/Curiously_recurring_template_pattern ). C++ 程序员将此称为Curiously Recurring Template Pattern ( https://en.m.wikipedia.org/wiki/Curiously_recurring_template_pattern )。 Don't worry it tends to melt everyone's mind the first time they encounter it.别担心,当每个人第一次遇到它时,它都会融化每个人的心。 And, if you don't use it for a while, it's not like riding a bike;而且,如果你有一段时间不使用它,它不像骑自行车; you need to learn it all over again你需要重新学习

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

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