简体   繁体   English

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

[英]C# generic class type parameter and constraint that is the same as the generic parameter

The Stripe payment .NET API has a generic class definition like below and I'd like to understand why the constraint part StripeEntity<T> should be the type T . Stripe payment .NET API 具有如下通用的 class 定义,我想了解为什么约束部分StripeEntity<T>应该是T类型。

public abstract class StripeEntity<T> : StripeEntity where T : StripeEntity<T>

From: https://github.com/stripe/stripe-do.net/blob/master/src/Stripe.net/Entities/_base/StripeEntity.cs来自: https://github.com/stripe/stripe-do.net/blob/master/src/Stripe.net/Entities/_base/StripeEntity.cs

I understand the generic syntax, but don't understand why the class is defined in this way, the thinking behind it.我理解通用语法,但不明白为什么 class 是这样定义的,背后的想法。 Is this a common pattern around generic classes and if so what are the benefits?这是泛型类的常见模式吗?如果是,有什么好处?

It's called the curiously recurring pattern , usually used in C++.它被称为奇怪的重复模式,通常用于 C++。

It has a couple of things going for it, especially the fact that it's a (very limited) form of static polymorphism, and so avoids the costs of calling virtual functions.它有几个优点,特别是它是 static 多态性的(非常有限的)形式,因此避免了调用虚函数的成本。 That has more value in C++ than in C# however, due to how the language and runtime are constructed.然而,由于语言和运行时的构建方式,C++ 比 C# 更有价值。

.Net also has better ways of dealing with this, for example you could achieve something similar in a cleaner way by using attributes and source generators. .Net 也有更好的方法来处理这个问题,例如,您可以通过使用属性和源生成器以更清晰的方式实现类似的东西。

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

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