C# 静态成员和非静态成员的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13155474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:47:36  来源:igfitidea点击:

Difference between static and non static members?

c#

提问by Ammar Raja

Possible Duplicate:
What's a static method in c#?

可能的重复:
c# 中的静态方法是什么?

I found it difficult to clear my mind about the actual concept of static and non-static(instance) members, after researching from so many forums i decided to put my question here:

我发现很难弄清楚静态和非静态(实例)成员的实际概念,在从这么多论坛上研究之后,我决定把我的问题放在这里:

What is the difference between static and non static members?

静态成员和非静态成员有什么区别?

采纳答案by Furqan Safdar

The staticmethods can by accessed directly from the class, while non-staticmethods (or instance methods as I like to call them) have to be accessed from an instance. That is why instatiating needs to be done for instance methods, while for static methods it's just not needed.

static方法可以由从类直接访问,而non-static方法(或实例方法如我喜欢把它们)必须从一个实例进行访问。这就是为什么需要对实例方法进行实例化,而对于静态方法则不需要。

In OOP, static variablesare used for values which cannot be stored by an instance variable. static methodscannot access instance methods or variables within a class. Of course that makes sense because that static method would not know which instance of the class we are trying to refer.

在 OOP 中,static variables用于不能由实例变量存储的值。static methods不能访问类中的实例方法或变量。当然这是有道理的,因为那个静态方法不知道我们试图引用类的哪个实例。

e.g. Supposed you wanted to keep a count of how many instances of a class exists? How would you store that in a single instance?

例如,假设您想计算一个类存在多少个实例?您将如何将其存储在单个实例中?

References:

参考:

  1. Static vs. Non-Static method in C#
  2. Static vs. non-static method
  1. C# 中的静态与非静态方法
  2. 静态与非静态方法

回答by Azodious

  • staticmembers are one per class but non-static members are one per instance.

  • staticmembers are accessed by their class name which encapsulates them, but non-static members are accessed by object reference.

  • staticmembers can't use non-static methods without instantiating an object, but non-static members can use staticmembers directly.

  • static constructoris used to initialize static fields, but for non-static fields normal instance constructor is used.

  • See herefor performance related points.

  • static成员每个类一个,但非静态成员每个实例一个。

  • static成员通过封装它们的类名访问,但非静态成员通过对象引用访问。

  • static成员不能在不实例化对象的情况下使用非静态方法,但非静态成员可以static直接使用成员。

  • static constructor用于初始化静态字段,但对于非静态字段,使用普通实例构造函数。

  • 有关性能相关的要点,请参见此处