[英]C# generic constraint: type parameter on the class inherits type parameter on the method?
[英]C# generic class type parameter and constraint that is the same as the generic parameter
Stripe payment .NET API 具有如下通用的 class 定义,我想了解为什么约束部分StripeEntity<T>
应该是T
类型。
public abstract class StripeEntity<T> : StripeEntity where T : StripeEntity<T>
来自: https://github.com/stripe/stripe-do.net/blob/master/src/Stripe.net/Entities/_base/StripeEntity.cs
我理解通用语法,但不明白为什么 class 是这样定义的,背后的想法。 这是泛型类的常见模式吗?如果是,有什么好处?
它被称为奇怪的重复模式,通常用于 C++。
它有几个优点,特别是它是 static 多态性的(非常有限的)形式,因此避免了调用虚函数的成本。 然而,由于语言和运行时的构建方式,C++ 比 C# 更有价值。
.Net 也有更好的方法来处理这个问题,例如,您可以通过使用属性和源生成器以更清晰的方式实现类似的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.