简体   繁体   English

C#sealed类创建其实例

[英]C# sealed class creating its instance

I know this is meaning less question, but I'm confused why sealed class create its instance. 我知道这意味着更少的问题,但我很困惑为什么密封类创建它的实例。

public sealed class SealedClass1
{
    static SealedClass1()
    {
    }

    public string GetmeassageFromSealed(string mesage)
    {
        return mesage;
    }
}

Here i decorate my constructor as private 在这里,我将我的构造函数装饰为私有

public sealed class SealedClass1
        {
            static SealedClass1()
            {

           }
      private Singleton()
            {

            }
            public string GetmeassageFromSealed(string mesage)
            {
                return mesage;
            }
        }

The sealed keyword in C# means that no class can inherit from that class. C#中的sealed关键字表示没有类可以从该类继承。

So if you have this scenario: 所以,如果您有这种情况:

public class Test { }

The following is valid 以下是有效的

public class NewTest: Test { }

However, as soon as you add the sealed keyword, the compiler with throw an error when trying to compile that library. 但是,只要添加sealed关键字,编译器就会在尝试编译该库时抛出错误。

public sealed class Test { }

public class NewTest: Test { }

This would throw 这会抛出

'NewTest' cannot inherit from sealed class 'Test'. 'NewTest'不能从密封类'Test'继承。

In short, the sealed keyword is a compile time check to ensure that there is no inheritence. 简而言之, sealed关键字是一个编译时检查,以确保没有继承。

可以实例化一个密封类,也可以从其他类继承,但它不能被其他类继承。

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

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