简体   繁体   English

成员由于保护级别错误而无法访问

[英]Member is inaccessible due to its protection level error

connected within this topic: How to connect string from my class to form在本主题中连接如何将我的班级中的字符串连接到表单

im trying to do solutions related to their answers (specifically answer of sir Jeremy) but this error keeps on appearing我试图做与他们的答案相关的解决方案(特别是杰里米爵士的回答),但这个错误不断出现

'KeyWord.KeyWord.keywords' is inaccessible due to its protection level “KeyWord.KeyWord.keywords”由于其保护级别而无法访问

code for KeyWords.cs: KeyWords.cs 的代码:

namespace KeyWord
{
    public class KeyWord
    {
        String[] keywords = { "abstract", "as", "etc." };

    }
}

code for main.cs main.cs 的代码

// Check whether the token is a keyword. 
var keyboardCls = new KeyWord.KeyWord();
String[] keywords = keyboardCls.keywords;

for (int i = 0; i < keywords.Length; i++)
{
    if (keywords[i] == token)
    {
        // Apply alternative color and font to highlight keyword.        
        rtb.SelectionColor = Color.Blue;
        rtb.SelectionFont = new Font("Courier New", 10, FontStyle.Bold);
        break;
    }
}

what should i do?我应该怎么办?

You need to define keywords as public您需要将keywords定义为 public

public String[] keywords = { "abstract", "as", "etc." };

Currently it is private and that is why not accessible outside the class.目前它是private ,这就是为什么不能在课堂外访问。

Access Modifiers (C# Programming Guide)访问修饰符(C# 编程指南)

Class members, including nested classes and structs, can be public, protected internal, protected, internal, or private.类成员,包括嵌套类和结构,可以是 public、protected internal、protected、internal 或 private。 The access level for class members and struct members, including nested classes and structs, is private by default .类成员和结构成员(包括嵌套类和结构)的访问级别默认为私有

Use this code instead:请改用此代码:

public class KeyWord
    {
        String[] keywords = { "abstract", "as", "etc." };

    }

The protection level for variable is private by default.变量的保护级别默认为private A good practice is using property for members in class.一个好的做法是为类中的成员使用属性。

You should make a property for Keywords as follows您应该为关键字创建一个属性,如下所示

public String[] Keywords
{
get{return keywords;}
}

its a protection violation as variables are private by default它违反保护,因为变量默认是私有的

Try to make the string-array public:尝试公开字符串数组:

public class KeyWord
{
    public String[] keywords = { "abstract", "as", "etc." };

}

您需要使用“public”关键字定义您的类

Please ensure the constructor is added as with public access specifier.请确保与公共访问说明符一样添加构造函数。 this could be a reason for this kind of error.这可能是导致此类错误的原因。 Example :例子 :

Customer() {
this.CustomerId = ++counter;
}
Change it to : 
public Customer() {
this.CustomerId = ++counter;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM