固定
它在"form1.designer.cs"的6个不同位置失败了。它说我需要静态使用它,所以我将所有错误从"this.xxxx"更改为"form1.xxxx"并且它起作用了。不确定我完全理解我做了什么...
固定
这里编程相当新手,只是在 C# 中处理一些基本的 OOP。我正在尝试从按钮单击事件中的另一个类调用方法。该方法传递一个参数,该参数是用户输入的文本。我认为问题与方法静态有关,但参数是动态的,因为它是用户输入的。请帮帮我!
public partial class Form1 : Form
{
string _yourName = textBox1.Text;
public Form1()
{
InitializeComponent();
}
private void Button1Click(object sender, EventArgs e)
{
if (DogCheckBox.Checked)
{
AnimalNoise.Bark(_yourName);
}
if (CatCheckBox.Checked)
{
AnimalNoise.Meow(_yourName);
}
if (FishCheckBox.Checked)
{
AnimalNoise.Girgle(_yourName);
}
}
}
public class AnimalNoise
{
public static void Bark(String name)
{
MessageBox.Show(name + " Bark");
}
public static void Meow(String name)
{
MessageBox.Show(name + " Meow");
}
public static void Girgle(String name)
{
MessageBox.Show(name + " Girgle");
}
}
首先,在实际创建textBox1
之前,您无法访问它。您应该在点击回调中捕获名称。我认为您看到的错误可能是因为代码中的某个地方您有其他称为AnimalNoise
的东西,您必须确保没有其他称为 AnimalNoise 的东西,并将 AnimalNoise 放在它自己的文件中。
你的确切问题没有明确说明,但我相信你从来没有设置过textBox1.Text。 在按钮单击事件期间设置它。
public Form1()
{
InitializeComponent();
}
private void Button1Click(object sender, EventArgs e)
{
string _yourName = textBox1.Text;
if (DogCheckBox.Checked)
{
AnimalNoise.Bark(_yourName);
}
if (CatCheckBox.Checked)
{
AnimalNoise.Meow(_yourName);
}
if (FishCheckBox.Checked)
{
AnimalNoise.Girgle(_yourName);
}
}
}