Main() 不想访问类变量
为什么我可以从“method()”而不是 Main() 方法访问 X 变量?
class Program
{
int X; // this is the variable I want access
static void Main(string[] args)
{
int a;
a = X; // this doesnt work, but why?
}
void metodo()
{
int b;
b = X; //this works, but why?
}
}
Why I can access to X variable from "method()" and not from Main() method?
class Program
{
int X; // this is the variable I want access
static void Main(string[] args)
{
int a;
a = X; // this doesnt work, but why?
}
void metodo()
{
int b;
b = X; //this works, but why?
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Try
X
是一个实例变量,这意味着类的每个实例都将拥有自己的X
版本。然而,Main 是一种静态方法,这意味着Program
类的所有实例都只有一个 Main,因此它访问X
是没有意义的,因为如果没有创建Program
实例,则可能有多个 X,也可能根本没有 X。将 X 本身设为静态意味着所有
Program
实例将共享X
,因此共享方法将能够访问它。Try
X
is an instance variable, which means that each and every instance of your class will have their own version ofX
. Main however, is a static method, which means, that there is only one Main for all instances of theProgram
class, so it makes no sense for it to accessX
, since there might be multiple X's or there might be none at all, if noProgram
instances are created.Making X itself static, means that all
Program
instances will shareX
, so the shared method will be able to access it.Main() 是一个静态函数。不能从静态函数访问非静态变量。
Main() is a static function. Non-static variables cannot be accessed from static functions.
假设您有一个包含两个变量的 Person 类:
眼睛数量属于该类(静态),而眼睛颜色属于每个实例。
如果将眼睛数量从 2 只更改为 3 只,那么世界上的每个人都会立即拥有 3 只眼睛,因为所有实例共享相同的静态变量。
如果将一个人实例的眼睛颜色从蓝色更改为红色,那么只有该人才会有红眼睛。
如果您能够访问静态方法内部的非静态成员,那么它的值会是多少?由于没有合理的答案,因此不允许发生这种情况。
Pretend you have a Person class with two variables:
The number of eyes belongs to the class (static) while the eye colour belongs to each instance.
If you change the number of eyes from 2 to 3 then every person in the world would instantly have 3 eyes because all of the instances share the same static variable.
If you change the eye colour of an instance of a person from blue to red then only that individual person will have red eyes.
If you were able to access non-static members inside of a static method what value would it take? Since there is no sane answer to that it is not allowed to happen.
X
和metodo()
都处于实例级别。Main()
处于静态级别。如果您希望X
可用于Main()
和metodo
,您需要将其声明为静态(即private static int X )。
Both
X
andmetodo()
are at the instance level.Main()
is at the static level. If you wantX
to be available for bothMain()
andmetodo
you would need to declare it as static (i.e.private static int X
).X
是一个实例变量,但Main
是一个静态方法,即它不与类Program
的任何特定实例关联。X
is an instance variable, butMain
is a static method, i.e. it's not associated with any particular instance ofclass Program
.要访问 X,您需要使用 static 关键字标记它或创建 Program 类的实例:
1.
2.
您应该阅读有关类成员和类实例成员的更多信息。
To have access to X you need either mark it by static keyword or create instance of Program class:
1.
2.
You should read more on class's members and on members of the class's instance.