c#中`static`是什么意思? [英] What does `static` mean in c#?

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

问题描述

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

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 个实例还是 100 万个实例,都存在 一个 类型的静态变量集(在 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.

静态变量初始化的确切点取决于是否还有静态构造函数,但从广义上讲,它是一次,通常在类中发生任何重大事件之前".(参见这篇博文以获得更详细的描述.)

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

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

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#中`static`是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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