所以我有这个代码
public partial class Form1 : Form
{
public string str;
public string str2;
public Form1()
{
InitializeComponent();
str = textBox1.Text;
str2 = textBox2.Text;
}
private void button1_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Enter Material Name Please.");
}
if (str == str2)
{
MessageBox.Show("Materials are equal.");
}
else if (str != str2)
{
MessageBox.Show("Materials don't match.");
}
}
}
我想你会猜到我在这里想做什么..你能说出它的错误吗?我几天前就开始了,原谅我缺乏知识。
答案 0 :(得分:5)
您只在构造函数中而不是在click-event处理程序中初始化这些字符串一次。您还可以使用属性将控件映射到字符串,从而使代码更具可读性和健壮性:
// use meaningful control/variable names
string Material1
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
string Material2
{
get { return textBox2.Text; }
set { textBox2.Text = value; }
}
private void button1_Click(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(Material1)) // handles also multiple spaces
{
MessageBox.Show("Enter Material Name Please.");
// return; <-- perhaps?
}
if (Material1 == Material2)
{
MessageBox.Show("Materials are equal.");
}
else
{
MessageBox.Show("Materials don't match.");
}
}