C#通用自引用声明 [英] c# generic self-referencing declarations

查看:50
本文介绍了C#通用自引用声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读Albaharis的 C#5.0 in a Nutshell,并且在泛型部分中遇到过,并且据说是合法的:

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

在这种情况下适当且有用的实际应用场景? / p>

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

推荐答案

这意味着 T 必须从继承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.

例如:

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

这篇关于C#通用自引用声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆