问题
Background
[Skip to Question if you're not interested in the background]
I stumbled across this generic class definition when reading the other day, and it stumped me for some time:
public abstract class Entity<T> where T : Entity<T>
I was puzzled as to how T
on Entity<T>
could be of Type Entity<T>
itself. It seemed some sort of bizarre recursive constraint.
I then realised that this constraint could be satisfied by subclassing (which is, of course, what abstract
is demanding of the class):
public class Deriver : Entity<Deriver>
Here, type T
is garanteed to be of type Entity<T>
because Deriver
derives from Entity<Deriver>
.
Question
Anyhow, it led me to wonder, if the class was not abstract, could we instantitate it directly?
So given
class Entity<T> where T : Entity<T>
Can we instantitate Entity<T>
directly?
Obviously we can't say:
Entity<SomeClass> e = new Entity<SomeClass>();
Because SomeClass
doesn't satisfy the constraint where T : Entity<T>
.
Ignoring the obvious "Why would you want to do that?" is this essentially is a way of ensuring a class is dervied before you can use it without using the abstract
keyword?
回答1:
That assumption is not correct. The following will compile:
var e = new Entity<Deriver>();
来源:https://stackoverflow.com/questions/14893081/instantiating-a-type-constrained-generic-class-without-subclassing-it