简体   繁体   中英

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.

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.

public sealed class Test { }

public class NewTest: Test { }

This would throw

'NewTest' cannot inherit from sealed class 'Test'.

In short, the sealed keyword is a compile time check to ensure that there is no inheritence.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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