开发者

Making a class not inherited

I am trying to crea开发者_如何学运维te a c# class, but I dont want it to be inherited. How can I accomplish that?


sealed is the word you're looking for, and a link for reference

public sealed class MyClass
{

}

And then just create your class as normal, however you won't be able to inherit from it.

You can however still inherit from a different class like so

public sealed class MyClass : MyBaseClass
{

}


Adding to the PostMan's answer, we can achieve the same by making the Class Constructor Private.

class NotInheritable
    {

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

 class Derived : NotInheritable { }

Now the class NotInheritable will not be inheritable, as the compiler will prompt the error:

NotInheritable.NotInheritable() is inaccessible due to its protection level.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜