简体   繁体   中英

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 .

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

I understand the generic syntax, but don't understand why the class is defined in this way, the thinking behind it. 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++.

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. That has more value in C++ than in C# however, due to how the language and runtime are constructed.

.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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