C#泛型class类型参数和与泛型参数相同的约束

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-dotnet/blob/master/src/Stripe.net/Entities/_base/StripeEntity.cs

我理解通用语法,但不明白为什么要这样定义class,背后的想法。这是围绕通用 classes 的常见模式吗?如果是,有什么好处?

称为the curiously recurring pattern,通常用于C++。

它有几个优点,尤其是它是一种(非常有限的)静态多态形式,因此避免了调用虚函数的成本。然而,由于语言和运行时的构造方式,这在 C++ 中比在 C# 中更有价值。

.Net 也有更好的方法来处理这个问题,例如,您可以通过使用属性和源生成器以更简洁的方式实现类似的效果。