質問

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?

役に立ちましたか?

解決

That assumption is not correct. The following will compile:

var e = new Entity<Deriver>();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top