为什么我们不能将密封类用作通用约束? [英] Why we can’t use sealed classes as generic constraints?
问题描述
您能猜出在泛型中不允许密封类作为类型约束的原因是什么?我只有一个解释是给使用裸约束的机会。
Can you guess what is the reason to not allow sealed classes for type-constraints in generics? I only have one explanation is to give opportunity to use naked constraints.
推荐答案
如果该类是密封的,则无法继承。如果无法继承,它将是对通用类型参数有效的唯一类型(假设允许作为类型参数)。如果它是唯一的泛型类型参数,那么将其设为泛型是没有意义的!您可以简单地针对非泛型类中的类型进行编码。
If the class is sealed it cannot be inherited. If it cannot be inherited it'd be the only type valid for the generic type argument [assuming if allowed to be a type argument]. If it is the only generic type argument then there's no point in making it generic! You can simply code against the type in non-generic class.
这里有一些代码。
public class A
{
public A() { }
}
public sealed class B : A
{
public B() { }
}
public class C<T>
where T : B
{
public C() { }
}
这将导致编译器错误:'B'
不是有效的约束。使用
作为约束的类型必须是接口,
a非密封类或
类型的参数。
除此之外,还不能将静态类作为泛型类型约束。原因很简单。在已编译的 IL 中,静态类被标记为抽象和密封,它们既不能实例化也不能继承。
In addition to this, You can also not have a static class as generic type-constraint. The reason is simple. Static classes are marked as abstract and sealed in compiled IL which can be neither instantiated nor inherited.
这是代码。
public class D<T>
where T : X
{
public D() { }
}
public static class X
{
}
这将导致编译器错误:'X':
静态类不能用作
约束。
这篇关于为什么我们不能将密封类用作通用约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!