“静态”在C#中是什么意思? [英] What does `static` mean in c#?

查看:113
本文介绍了“静态”在C#中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的对C#中static关键字的真实含义感到困惑。我在互联网上浏览了不同的文章,但是没有一篇文章能真正帮助我理解它的含义,其他来源也不可信。我知道Stack Overflow有一些出色的头脑,可以帮助我理解static的真正含义,例如

I am really confused with the real meaning of the static keyword in C#. I have gone through different articles on internet but none of them are really helping me to understand it's meaning and other sources are not trusted. I know Stack Overflow has some brilliant minds who can help me understand the real meaning of static like


  • 初始化时。

  • 静态方法,属性,类和构造函数

  • 静态vs只读vs常量

推荐答案

简而言之,静态有效地表示与一种类型关联,而不是该类型的任何实例。因此,无论您有0个实例还是一百万个实例,一个类型(在AppDomain中)的一组静态变量都是 个;您不需要实例就可以访问静态成员,等等。

In short, static effectively means "associated with a type instead of any one instance of the type". So there's one set of static variables for a type (within an AppDomain) whether you have 0 instances or a million; you don't need an instance to access a static member, etc.

静态变量初始化的 exact 确切点取决于是否还有是否使用静态构造函数,但从广义上讲,它是一次,通常在类中没有任何重大事件发生之前。 (请参阅此博客文章

The exact point of initialization of static variables depends on whether there's also a static constructor or not, but very broadly speaking it's "once, usually before anything significant happens in the class". (See this blog post for a more detailed description.)

readonly 字段可以是静态的也可以是实例的(即与类型有关)或与该类型的实例相关), const 值始终是 隐式静态的(它们是编译时常量,因此不会每个实例只有一个副本是很有意义的。)

While readonly fields can be either static or instance (i.e. related to the type or related to an instance of the type), const values are always implicitly static (they're compile-time constants, so it wouldn't make sense to have one copy per instance).

您有时可能会看到静态被描述为所有共享类型的实例-我个人不喜欢这种描述,因为它暗示必须至少有一个实例...而实际上,您不需要任何实例以使用静态成员。我更喜欢将它们视为完全独立的,而不是在实例之间共享。

You may sometimes see static being described as "shared between all instances of a type" - I personally dislike that description, as it suggests that there has to be at least one instance... whereas actually, you don't need any instances in order to use a static member. I prefer to think of them as entirely separate, rather than being "shared" between instances.

这篇关于“静态”在C#中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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