一些逻辑 OOP 概念
我有一个问题。
class A
{
static void m1()
{
int x=10;
}
}
class B
{
// if i want to access the variable x in b class how can i access it
A a = new A();
// a. what should i write here to access x variable
}
I have a question.
class A
{
static void m1()
{
int x=10;
}
}
class B
{
// if i want to access the variable x in b class how can i access it
A a = new A();
// a. what should i write here to access x variable
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为了访问
x
,您必须将其设置为A
上的字段:但是,从类中公开公共字段通常是不好的做法 - 最好将该字段包装在封装它的属性:
如果这个语法看起来很麻烦,你可以稍微简化一下。 C# 有一个名为“自动实现属性”的功能,如果您执行以下操作,编译器将为您生成上面的代码:
In order to access
x
you must make it a field onA
:However it is generally bad practice to expose public fields from a class - it is better to wrap the field in a property to encapsulate it:
If this syntax seems cumbersome you can simplify it a bit. C# has a feature called automatically implemented properties in which the compiler will generate the code above for you if you do this:
它应该是属性或公共变量。
It should be either property or a public variable.
首先,提出问题时,请花 30 秒的时间正确。你的代码就是废话。
call
不是 C# 中的有效关键字。您指的是class
吗?或者其他什么?其次,要求您通过拼写检查器运行文本是否不合理?我们没有人会因为回答您的问题而获得报酬,我们是在自己的空闲时间免费做的。因此,如果您想要答案,请让我们轻松理解并回答您的问题。不要因为我们的懒惰而付出代价,因为那样我们也会偷懒,并忽略你的问题。现在,据我了解你的问题,你不能。
x
是在函数内部声明的局部变量。在其他地方是看不到的。First, when asking a question, please spend just 30 seconds trying to get it right. Your code is nonsense.
call
isn't a valid keyword in C#. Did you meanclass
? Or something else? Second, is it unreasonable to ask you to run the text through a spell checker? None of us are getting paid to answer your questions, we're doing it for free, in our own free time. So if you want answers, make it easy for us to understand and answer your questions. Don't be lazy at our expense, because then we'll be lazy too, and ignore your question.Now, as I understand your question, you can't.
x
is a local variable declared inside the function. It's not visible anywhere else.exmaple 使用实例变量,而不是静态变量。
要访问静态变量,您必须有一个静态方法 M1,然后在 ClassB 中您可以使用类名而不是对象名来访问 x 变量,如下所示:
变量 x1 也必须声明为静态,如: public static x = 10;
The exmaple uses instance variables , not static.
To access static variables you must have a static method M1 then in ClassB you access the x variable usign the class name not the object name, like this:
Variable x1 must also be declared as static like: public static x = 10;