问题
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