为什么我们不能创建静态类在.net中的实例 [英] Why we cannot create the Instance of the Static Class in .Net

查看:750
本文介绍了为什么我们不能创建静态类在.net中的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据MSDN的

类可以声明为static,表明它仅含   静态成员。它是不可能创建的静态实例   类使用new关键字。静态类是自动加载   由.NET Framework公共语言运行时(CLR)程序时   或包含类的命名空间被加载。

"A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language run-time (CLR) when the program or namespace containing the class is loaded."

做了一些研究之后,我发现,静态类不包含实例构造函数。我不明白为什么静态类不包含实例构造函数和什么用static关键字的。为什么.NET不允许我们创建一个静态类的实例?

After doing some research on it, I find that static classes does not contains the instance constructor. I do not understand why static classes does not contains the instance constructor and what is the use of the static keyword. Why .Net does not allow us to create the instance of a static class?

推荐答案

静态类不包含任何实例成员的属性或功能。因此,为了使一个实例是没有意义的。

Static classes do not contain any instance member properties or functions. So to make an instance would be pointless.

静态类用于包含有同样的效果在你的程序变量,特性和功能。

Static classes are used for containing Variables, properties and functions that have the same effect all over your program.

例如,你可以有一个设置类。

For example you can have a "Settings" class.

这是拥有所有静态属性。

That has all static properties.

当它被访问(通过静态构造函数) 从磁盘自动加载设置文件或重置为默认设置,如果未找到该文件。

When it is accessed (via static constructor) Automatically loads the settings file from disk or resets to default settings if the file is not found.

现在来自全国各地的程序,你可以只调用访问这个类

now from all over your program you can access this class by just calling

  • Settings.ScreenSize
  • Settings.RootPath

您甚至可以创建一个函数

You can even create a function

  • Settings.Save(),以将设置保存到磁盘下次使用。
  • Settings.Reset()来恢复默认设置。

这样做的好处是,你所有的设置都将被归纳在一个地方,所有的逻辑设置放置在一个地方。你将永远知道,有设置类只有一个无论你叫它实例

The advantage of this is that all your settings will be grouped in one place and all logic for your settings is placed in one spot. You will always know that there is only one instance of the settings class from wherever you call it

我希望这有助于

这篇关于为什么我们不能创建静态类在.net中的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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