简体   繁体   中英

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

code for KeyWords.cs:

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

    }
}

code for 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

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

Currently it is private and that is why not accessible outside the class.

Access Modifiers (C# Programming Guide)

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 .

Use this code instead:

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

    }

The protection level for variable is private by default. 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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