Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've been reading Albaharis' "C# 5.0 in A Nutshell" and I've encountered this in Generics section and it is said to be legal:

class Bar<T> where T : Bar<T> { ... }

And it meant nothing to me, although I've read the whole chapter carefully. I couldn't understand even a bit of it.

Can someone please explain it with some understandable naming, like:

class Person<T> where T : Person<T> { ... }

And a real-world application scenario where this usage is appropriate and useful?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
233 views
Welcome To Ask or Share your Answers For Others

1 Answer

It means that T must inherit from Person<T>.

This is a typical way to create type-specific methods or properties or parameters in the base class, specific to the actual descendant.

For instance:

public abstract class Base<T> where T : Base<T>, new()
{
    public static T Create()
    {
        var instance = new T();
        instance.Configure(42);
        return instance;
    }

    protected abstract void Configure(int value);
}

public class Actual : Base<Actual>
{
    protected override void Configure(int value) { ... }
}

...

 Actual a = Actual.Create(); // Create is defined in Base, but returns Actual

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...