Instantiating a type-constrained generic class without subclassing it

痴心易碎 提交于 2019-12-14 03:16:31

问题


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

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