简体   繁体   English

实例化类型约束的泛型类,而不对其进行子类化

[英]Instantiating a type-constrained generic class without subclassing it

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. 我很困惑T on Entity<T>如何成为Type Entity<T>本身。 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): 然后我意识到这个约束可以通过子类化来满足(当然,这是abstract对类的要求):

public class Deriver : Entity<Deriver>

Here, type T is garanteed to be of type Entity<T> because Deriver derives from Entity<Deriver> . 这里,类型T保证是Entity<T>类型,因为Deriver派生自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? 我们可以直接实现Entity<T>吗?

Obviously we can't say: 显然我们不能说:

Entity<SomeClass> e = new Entity<SomeClass>();

Because SomeClass doesn't satisfy the constraint where T : Entity<T> . 因为SomeClass不满足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? 这本质上是一种在不使用abstract关键字的情况下使用它之前确保类被省略的方法吗?

That assumption is not correct. 这个假设是不正确的。 The following will compile: 以下将编译:

var e = new Entity<Deriver>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM