为什么我们不能用密封类为一般限制? [英] Why can't we use sealed classes as generic constraints?

查看:176
本文介绍了为什么我们不能用密封类为一般限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能猜到是不允许的密封类类型的限制仿制药的原因是什么?我只有一个解释,就是给机会,使用明火的限制。

解决方案

如果类是密封的不能被继承。如果它不能被继承这将会是唯一的一种有效的泛型类型参数[假设如果允许是一个类型参数。如果它是唯一的泛型类型参数再有就是在使之成为通用没有意义!你可以简单地code对非泛型类的类型。

下面是一些code这一点。

 大众A级
{
    公开发行A(){​​}
}

公共密封类B:
{
    市民B(){}
}

公共类℃下T>
        其中T:乙
{
    市民C(){}
}
 

  

这将使编译器错误:B   不是有效的约束。使用A型   作为约束必须是一个接口,   非密封类或类型   参数。

除此之外,你也可以没有一个静态类作为泛型类型约束。原因很简单。 静态类在编译的 IL 这既不能实例化,也没有继承标记为摘要密封

这里的code这一点。

 公共类D< T>
        其中,T:X
{
    公共D(){}
}

公共静态类X
{
}
 

  

这将使编译器错误:X:   静态类不能被用作   约束。

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.

Here's some code for this.

public class A
{
    public A() { }
}

public sealed class B : A
{
    public B() { }
}

public class C<T>
        where T : B
{
    public C() { }
}

This will give compiler error: 'B' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.

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.

Here's the code for this.

public class D<T>
        where T : X
{
    public D() { }
}

public static class X
{
}

This will give compiler error:'X': static classes cannot be used as constraints.

这篇关于为什么我们不能用密封类为一般限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆