抽象类不能在C#中被封了? [英] Abstract class cannot be sealed in c#?

查看:206
本文介绍了抽象类不能在C#中被封了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读的地方

摘要和sealed修饰符相当于一类是静态的

我还发现,

在声明静态类,内部编译器标志着类抽象和密封,并在IL code创建一个私有的构造函数

所以,我决定做这一点:

so, I decided to do this:

static class A
{
    public static void test()
    {
        Console.WriteLine("test");
    }
}

现在,A级不能被继承,也不实例。

所以,让我们写了 B类使用摘要来prevent实例化和使用密封来prevent继承。

So, let us write a class B using abstract to prevent instantiation and using sealed to prevent inheritance.

不过,这种方法失败。

其中应该相当于

public abstract sealed class B
{
    private B()
    {

    }
    public void test()
    {
        Console.WriteLine("test");
    }
}

但是我收到一个错误,指出错误CS0418: B:一个抽象类不能被密封或静态的`。任何想法,为什么这是不可能的?

But I recieve an error stating "error CS0418:B': an abstract class cannot be sealed or static"` . Any ideas why this is not possible ?

在此先感谢您的回答。

推荐答案

检查过System.Directory类的白细胞介素(这是静态的),它是在IL声明为:

Having checked the IL of the System.Directory class (which is static), it is declared in IL as:

.class public auto ansi abstract sealed beforefieldinit System.IO.Directory
extends System.Object
{
    ...

此外,这篇文章(<一href="http://msdn.microsoft.com/en-us/library/ms229038.aspx">http://msdn.microsoft.com/en-us/library/ms229038.aspx)表明CLR处理静态类为抽象的密封类,支持不支持直接delcaring静态类语言(如C ++)。

Further, this article (http://msdn.microsoft.com/en-us/library/ms229038.aspx) suggests that the CLR handles static classes as abstract sealed classes to support languages that do not support directly delcaring static classes (eg C++).

因此​​,在总结,静态类在C#中的语法糖密封抽象类有私有构造函数。我个人很高兴了,作为静是一个更容易编写和一个更容易得到正确的。

Thus in conclusion, static classes in C# are syntactic sugar for sealed abstract classes with private constructors. I for one am glad of that as "static" is a lot easier to write and a lot easier to get right.

这篇关于抽象类不能在C#中被封了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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