gpt4 book ai didi

c# - 由于其保护级别而无法访问?

转载 作者:行者123 更新时间:2023-12-03 23:15:30 26 4
gpt4 key购买 nike

一般来说,我对编码还是很陌生,虽然这个简单的程序只是为了测试构造函数的工作原理,但我仍然想知道为什么会出现这个错误。

    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。这些变量似乎是在公共(public)类中声明的,那么为什么不能访问它们呢?我试图寻找解决方案,但我发现的所有问题都太复杂了,以至于我无法得到可以转化为我自己理解的答案。
所有帮助表示赞赏!

最佳答案

即使变量在公共(public)类中,它们也必须声明为公共(public)的,因为它们默认是私有(private)的。

见:Access Modifiers

Class members, including nested classes and structs, can be public, protected internal, protected, internal, or private. The access level for class members and struct members, including nested classes and structs, is private by default.



最好使用大写名称和 properties对于公共(public)变量。
public A { get; set; }

属性允许您控制成员的读/写访问,以及在读取或设置它们时添加逻辑。

关于c# - 由于其保护级别而无法访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31302825/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com