总体来说,我对编码还是很陌生的,尽管这个简单的程序仅是用来测试构造函数的工作方式,但我仍然想知道为什么会出现此错误。
I'm still quite new to coding in general, and while this simple program is only meant to be a test to learn how constructors work, I'd still like to know why I'm getting this error.
using System; public class methodTest { int a; int b; int c; public methodTest(int i, int j, int k) { a = i; b = j; c = k; } } public class methodObj { static void Main() { methodTest obj = new methodTest(10, 20, 30); Console.WriteLine("obj = " + obj.b); Console.ReadKey(); } }我不确定我为什么会得到错误。问题出在Console.WriteLine上,它指出它无法访问obj.b。变量似乎是在公共类中声明的,那么为什么不能访问它们呢?我试图寻找解决方案,但是我发现的所有问题都让我很困惑,无法获得可以转化为我自己的理解的答案。 感谢所有帮助!
I'm not entirely sure why I'm getting the error. The problem is with the Console.WriteLine, where it states it cannot access obj.b. The variables seem to be declared within a public class, so why can they not be accessed? I tried searching for a solution to this, but all the questions I found were much too convoluted for me to get an answer I could translate to my own understanding. All help appreciated!
推荐答案即使变量在公共类中,也必须将它们声明为公共,因为默认情况下它们是私有的。
Even though the variables are in a public class, they must be declared as public as they are private by default.
请参阅:访问修饰符
类成员,包括嵌套的类和结构,可以是公共的,受保护的是内部的,受保护的,内部的或私有的。 类成员和结构成员(包括嵌套类和结构)的访问级别默认情况下为私有。
最佳做法是使用大写名称和属性表示公共变量。
It is best practice to use capitalized names and properties for public variables.
public A { get; set; }属性可让您控制成员的读/写访问,并添加逻辑读取或设置它们时。
Properties allow you to control the access of reading/writing of the member, as well as adding logic when they are read or set.
更多推荐
由于其保护级别而无法访问?
发布评论