c#标签文本卡住
本文关键字:文本 标签 | 更新日期: 2023-09-27 18:08:49
我一直在学习如何创建类和继承。现在我面临的问题printbase方法不工作在我的代码,标签文本没有改变什么是我做的错误?这段代码的工作方式是new dog方法根据一个组合框项创建一个新狗的名字它使用它的名字,生成数字并召唤一个叫做bark的方法,如果我点击按钮它调用print base方法并改变标签的文本但它不起作用。有什么想法吗?
public partial class Form1 : Form
{
class animal : Form1
{
public string name;
public int age;
public string action;
public void printbase(string whatname, int whatage, string whataction)
{
namelabel.Text = whatname;
agelabel.Text = whatage.ToString();
actionlabel.Text = whataction;
}
}
class dog : animal
{
public string dogaction;
public void bark()
{
dogaction = "wuff";
}
public void newdog()
{
Random x = new Random();
string names;
names = dogscombo.Text;
dog hey = new dog();
hey.name = names;
hey.age = x.Next(1,10);
bark();
hey.action = dogaction;
printbase(hey.name, hey.age, hey.action);
}
}
public Form1()
{
InitializeComponent();
}
private void getbutton_Click(object sender, EventArgs e)
{
switch (dogscombo.SelectedIndex)
{
case (0):
dog u = new dog();
u.newdog();
break;
}
}
}
您应该创建独立的类animal,而不是继承它的类dog。在您的示例中,类animal基于类Form1。因此,程序创建新的表单,但不显示给用户。如果你不使用t intend to create new form, don
,不要使用类Form1作为类animal的基类。如果您确实打算这样做,那么调用方法将新创建的表单显示给用户。下面的代码可以工作:
private void getbutton_Click_1(object sender, EventArgs e)
{
switch (dogscombo.SelectedIndex)
{
case (1):
dog u = new dog();
u.newdog();
u.Show();
break;
}
}