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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15130231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:10:21  来源:igfitidea点击:

Member is inaccessible due to its protection level error

c#.netcsharpcodeprovider

提问by

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?

我该怎么办?

采纳答案by Habib

You need to define keywordsas public

你需要定义keywords为 public

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

Currently it is privateand 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. The access level for class members and struct members, including nested classes and structs, is private by default.

类成员,包括嵌套类和结构,可以是 public、protected internal、protected、internal 或 private。类成员和结构成员(包括嵌套类和结构)的访问级别默认为私有

回答by Tomtom

Try to make the string-array public:

尝试公开字符串数组:

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

}

回答by Sayse

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

它违反保护,因为变量默认是私有的

回答by Herks

Use this code instead:

请改用此代码:

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

    }

The protection level for variable is privateby default. A good practice is using property for members in class.

变量的保护级别是private默认的。一个好的做法是为类中的成员使用属性。

回答by Mohit Yadav

You need to define the your class with "public" keyword

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