最好以防止被实例化一个类的方法吗? [英] Best way to prevent a class from being Instantiated?

查看:232
本文介绍了最好以防止被实例化一个类的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道如何防止一类在.NET中被实例化?

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 achieve this?

推荐答案

制作类的静态为最好的办法,如果你的绝对的不希望任何实例。这从创建实例站的任何的。本课程将被密闭的的抽象的,不会有的构造函数。

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 :)

请参阅的 MSDN 有关静态类的更多信息。

See MSDN for more information about static classes.

这篇关于最好以防止被实例化一个类的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆