使一个类不被继承

问题描述 投票:26回答:2

我正在尝试创建一个c#类,但我不希望它被继承。我怎么能做到这一点?

c# class inheritance
2个回答
36
投票

sealed是您正在寻找的单词,以及reference的链接

public sealed class MyClass
{

}

然后像往常一样创建你的类,但是你将无法继承它。

但是,您仍然可以从其他类继承

public sealed class MyClass : MyBaseClass
{

}

0
投票

加上PostMan's答案,我们可以通过使achieveConstructor来使Private相同。

class NotInheritable
    {

        private NotInheritable()
        {
            //making the constructor private
        }
    }

 class Derived : NotInheritable { }

现在班级NotInheritablenot be inherited.

© www.soinside.com 2019 - 2024. All rights reserved.