为什么静态变量共享给所有类的实例 [英] Why static variables are shared to the all instance of class

查看:261
本文介绍了为什么静态变量共享给所有类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般情况下,静态变量会在课程开始时被内化,但为什么要分享



类的实例的静态变量



我尝试过的事情:



一般情况下,无论何时上课,静态变量都会被内部化,但为什么要共享



类的实例的静态变量

Generally static varibles are intalized whenever the class excuted but why should share

the static varibles to the instances of the class

What I have tried:

Generally static varibles are intalized whenever the class excuted but why should share

the static varibles to the instances of the class

推荐答案

因为这就是它们的用途。

静态变量是所有实例共有的变量,或者不需要该类实例才能使用的变量。



想想汽车片刻:

Because that is what they are there for.
Static variables are ones which are common to all instances, or that don't require an instance of the class in order to be used.

Think of cars for a moment:
How many wheels has a car?



这很简单 - 全部汽车有四个轮子:如果他们有一个,他们会摔倒,两个他们将是摩托车,三个将使他们成为三轮车,五个或更多意味着他们属于好莱坞,而不是在路上。您不需要询问有关特定汽车的问题,因为所有汽车都共享相同的信息。


That's simple - all cars have four wheels: if they had one, they would fall over, two and they would be motorcycles, three would make them a tricycle, and five or more means they belong in Hollywood, rather than on the road. You don't need to ask the question about a specific car, because all cars share the same information.

What color is a car?



那更难,因为我的车是红色的,你的车是蓝色的,这辆车是绿色的,等等 - 汽车的颜色取决于你是哪辆车参考。



在C#术语中, NumberOfWheels 属性是 static - 由所有实例共享并通过类名访问:


That's harder, because "my car" is red, "your car" is blue, "this car" is green, and so on - the color of the car depends on exactly which car you are referring to.

In C# terms, the NumberOfWheels property is static - shared by all instances and accessed via the class name:

Console.Writeline(Car.NumberOfWheels);

颜色属性是非静态的(基于实例),需要使用该类的特定实例:

While the Color property is non static (instance based) and requires a specific instance of the class to use:

Car myCar = new Car(...);
Car yourCar = new Car(...);
...
Console.WriteLine("My car is {0}, your car is {1}", myCar.Color, yourCar.Color);



有意义吗?


Make sense?


引用:

为什么



因为语言是这样设计的!

这些变量是静态的,因为它们与类中的普通变量不同。

它们的存在是因为设计师遇到了他们的需要。

如果你不需要它们,就不要使用它们。



为什么春天会成功到冬天?


Because the language is designed that way !
these variables are static because they are different from ordinary variable in classes.
They exist because the designers have encountered their need.
If you don't need them, just don't use them.

Why Spring succeed to Winter ?


这篇关于为什么静态变量共享给所有类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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