为什么这在C#(通用类和自引用)中有效? [英] Why this works in C# (generic class and self-reference)?

查看:61
本文介绍了为什么这在C#(通用类和自引用)中有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

class X<T> : Base
{
//For exemple:
    static T something();
}

我可以拥有

class A : X <A> 
{
}

从逻辑上讲,像这样:

class A : Base
{
    static A something();
}

这很好用.

但是我的理解是一种自我参照(A是X的孩子,而X在A ...之前不存在),这打破了计算机科学的基础,所以我想知道我的理解错了吗?

But in my comprehension, it's kind of self-reference (A is the children of X, while X doesn't exists before A...), which is breaks the foundation of computer science, so I want to know what's wrong with my comprehension??

推荐答案

完全没问题.您也可以在没有泛型的情况下进行类似操作:

It's totally fine. You can do similar without generics too:

class Test
{
    public static Test GetInstance()
    {
        return new Test();
    }
}

我在这里看不到任何自我参考.实际上这是一个非常有用的模式,例如在实现单例时.简化的概念(我知道,它应该使用锁等):

I don't see any self-reference here. And actually it's quite useful pattern e.g. when implementing singletons. Simplified concept (I know, it should use locks, etc...):

public static class Singleton<T> where T : new()
{
    private static T _instance;

    public static T GetInstance()
    {
        return _instance ?? (_instance = new T());
    }
}

编辑-回答您的评论问题:

X< T> 已经存在 .合适的是,我指的是每种类型的适合通用约束(或没有约束时仅适用于每种类型).而且,我的意思是,不仅装配中的所有类都可用.只需每个合适的类型.

X<T> already exists for all suitable T parameters. By suitable I mean every type that suits generic constraint (or just every type when there is no constraint). And by every I mean not only all classes available within your assembly. Just every suitable type.

通用类/方法只是一个模板,可以在运行时针对特定的通用类型进行解析.这就是为什么您甚至不必在声明了它的汇编中使用泛型类的原因.这就是为什么您的代码可以正常工作的原因.

Generic class/method is just a template which is resolved for given particular generic type in runtime. That's why you don't have to even use the generic class at all in assemble it's declared within. And that's why your code works fine.

这篇关于为什么这在C#(通用类和自引用)中有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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