Why this works in C# (generic class and self-reference)?

为君一笑 提交于 2021-02-17 04:59:29

问题


I have

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

And I can have

class A : X <A> 
{
}

To logically have something like this:

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

This works and works well.

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


回答1:


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());
    }
}

Edit - Answering your comment question:

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.



来源:https://stackoverflow.com/questions/18666227/why-this-works-in-c-sharp-generic-class-and-self-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!