Best way to prevent a class from being Instantiated?

后端 未结 5 1959
北海茫月
北海茫月 2020-12-14 20:20

I need to know how to prevent a class from being Instantiated in .net?

I know few methods like making the class Abstract and Static.

Is there any more way to

5条回答
  •  眼角桃花
    2020-12-14 21:15

    Marking the constructor private. Of course, this doesn't prevent the class from instantiating itself through a static method, for example...

    More practically, what's the purpose of disallowing class instantiation. If it's to have a singleton, then a private constructor is appropriate. If it's to force subclassing, making the class abstract is better; if it's to have a class with utility methods, making it static is one way (then you can only have static methods).

提交回复
热议问题