Best way to prevent a class from being Instantiated?

后端 未结 5 1956
北海茫月
北海茫月 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:05

    Making the class static is the best approach, if you absolutely don't want any instances. This stops anyone from creating instances. The class will be both sealed and abstract, and won't have any constructors.

    Additionally, the language will notice that it's a static class and stop you from using it in various places which imply instances, e.g. type arguments and variables. This indicates the intention more clearly than just having a private constructor - which could mean that there are instances, created within that class (e.g. for a singleton implementation).

    Oh, and making the class static will stop you from introducing any pointless instance members in the class, too :)

    See MSDN for more information about static classes.

提交回复
热议问题