How to connect string from my class to form

2019-07-23 15:12发布

问题:

I've been working on this stringcodes in program:

string[] keywords = { "abstract", "as", "etc" };

and its working the time i use it after this code (in mainform.cs):

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;
    }
}

but thing is i want to make separate class (KeyWord.cs) for keywords and declare it in mainform but this code not working:

KeyWord.cs:

namespace editor
{
    class KeyWord
    {
        string[] keywords = { "abstract", "as", "etc" };
    }
}

Mainform.cs:

string[] 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;
    }
}

Error says:

Use of unassigned local variable 'keywords':

note that this code was under of a void condition in mainform:

private void TextChangedEvent(object sender, EventArgs e)
{
}

What should i do?

回答1:

Welcome to Stackoverflow, you need to get an instance of the KeyWord class and then assign its Keywords string array to your locally declared String[] keywords in Mainform.cs, eg:

     var keyboardCls = new editor.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;
            }
        }

Edit:

The Type or namespace name 'KeyWords' could not be found.

namespace editor //<- remove the namespace or make it the same as frmMain.cs's namespace or fully qualify the namespace when instantiating new editor.KeyWord();

I've edited my code to show the last option. Also if the KeyWord.cs is in a different project to the MainForm.cs then you will need to add a Reference.



回答2:

If you want to just call the object and only have one instance of it, use the static keyword. Either way, you're going to have to assign it a value before you use it.

string[] keywords = new string[3];

3 being the predetermined length of the array. If you need a variable length, use List<T>. This is only going to help you for now, though. The best thing for you to do is start reading some books or tutorials.