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

编程入门 行业动态 更新时间:2024-10-26 21:20:32
本文介绍了由于其保护级别而无法访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

总体来说,我对编码还是很陌生的,尽管这个简单的程序仅是用来测试构造函数的工作方式,但我仍然想知道为什么会出现此错误。

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.

更多推荐

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

本文发布于:2023-11-26 19:57:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634974.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:于其   无法访问   级别

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!