静态和非静态成员之间的区别?

Amm*_*aja 9 c#

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

我发现很难清楚我对静态和非静态(实例)成员的实际概念的看法,经过这么多论坛的研究,我决定在这里提出我的问题:

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

Fur*_*dar 11

The static methods can by accessed directly from the class, while non-static methods (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.

In OOP, static variables are used for values which cannot be stored by an instance variable. static methods cannot 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.

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. 静态与非静态方法


Azo*_*ous 7

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

  • static 成员可以通过它们的类名来访问它们,但是通过对象引用来访问非静态成员.

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

  • static constructor 用于初始化静态字段,但对于非静态字段,使用常规实例构造函数.

  • 请参阅此处了解性能相关点.