向C#应用程序添加类时出现的问题[关闭]

问题描述 投票:-1回答:1

我正在尝试创建一个生成单词作为标签组件的对象,并在单击按钮时将其显示在屏幕上。

如果我把代码放在事件BtnStart_Click内,它工作正常,但是当我尝试用相同的代码创建一个类WordGenerator它不会工作。

如果我将鼠标放在"words[0] = new ...."类的WordGenerator上,它会给msgbox说“当前上下文中不存在名字'字'。”我不明白为什么会这样。在前一行中,我声明'words'是一个标签数组。

follow a picture to illustrate my problem

c# class object
1个回答
1
投票

你不能这样做,使用构造函数初始化成员变量,如下所示:

public WordGenerator()
{
   this.words[0] = new Label();
   // rest of initializations here
}

或者您可以使用方法来完成初始化:

public void InitializeWords()
{
   this.words[0] = new Label();
   // rest of initializations here
}
© www.soinside.com 2019 - 2024. All rights reserved.