简体   繁体   English

为什么密封类不允许是泛型类型约束?

[英]Why sealed classes are not allowed to be generic type constraints?

I just wanted to know why sealed classes are not allowed to be generic type constraints? 我只是想知道为什么密封类不允许是泛型类型约束?

Let's suppose i have a simple code snippet in c# as bellow 假设我在c#中有一个简单的代码片段,如下所示

 public sealed class Base
{
    public Base() { }
}

public class Derived<T>
        where T : Base
{
    public Derived() { }
}

When i am instantiating the Derivedclass i am getting 'Base' is not a valid constraint. 当我实例化Derivedclass时,我得到'Base'不是一个有效的约束。 A type used as a constraint must be an interface, a non-sealed class or a type parameter. 用作约束的类型必须是接口,非密封类或类型参数。

Because then there's no point in it being generic. 因为那时通用没有任何意义。 T could only be Base , so you might as well make it a non-generic type to start with. T 只能Base ,因此您可以将其作为非泛型类型开始。

Why would you want Derived to be generic here? 为什么你希望 Derived在这里是通用的? Why would you want a type called Base (implying that it should be a base type) to be sealed? 为什么你会想要一个名为类型Base (这意味着它应该是一个基本类型)被封了?

Because T will never have child classes! 因为T永远不会有子课! There's no point to have such kind of generic. 没有必要拥有这种通用。

The compiler doesn't want to go through the trouble of making something generic if there's only one class it can ever be. 如果只有一个类,那么编译器不想经历制作通用的麻烦。 Note that one can use a sealed class as a generic constraint if the sealed class is passed as a type parameter. 请注意,如果将密封类作为类型参数传递,则可以使用密封类作为通用约束。 For example, if one has a class 例如,如果有一个班级

Class Foo(Of T, U As T)

one may create an instance of that class where both generic type parameters are the same sealed type, since one could also create instances where the type parameters refer to different types. 可以创建该类的实例,其中两个泛型类型参数都是相同的密封类型,因为还可以创建类型参数引用不同类型的实例。

T cant be anything else but Base . T不能是别的什么,只是Base So, whats the point making it Generic ? 那么,是什么让它成为Generic?

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

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