这段代码似乎很可疑,我不知道如何解决它。
基本上,player.Name应该从TextBox中获取参数并将其插入其中,但似乎它不会做任何类似的事情...或者我可能会以错误的方式检查...
private void textBox1_TextChanged(object sender, EventArgs e)
{
Player player = new Player();
player.Name = textBox1.Text; //Problematic line
}
private void Button_Start_Click(object sender, EventArgs e)
{
Player player = new Player();
switch (player.Name.ToUpper())
{
case "N/A": Label_Question.Text = "Please set your name!"; break;
default: Label_Question.Hide(); goto QuizStart;
}
QuizStart:
{
}
}
答案 0 :(得分:2)
问题是你在textchanged和按钮按下事件上创建了一个新的“Player”实例,这意味着按下按钮的玩家总是为空。
这样的事情应该为你解决问题:
//It's called interface
type Parent interface{
doSomething() string
}
//Use interface before defining implementation
func JustPrint(p Parent){
fmt.Println(p.doSomething())
}
//Define MyChild
type MyChild SomeType
//You do not have to implement interface explicitly
//Just to define method needed would be enough
func (mc MyChild) doSomething() string{
return "Test"
}
或者为什么不一起跳过textchanged(除非你想在这里没有显示的代码中做其他事情):
Player player;
private void textBox1_TextChanged(object sender, EventArgs e)
{
player = new Player();
player.Name = textBox1.Text; //Problematic line
}
private void Button_Start_Click(object sender, EventArgs e)
{
switch (player.Name.ToUpper())
{
case "N/A":
Label_Question.Text = "Please set your name!";
return;
default:
Label_Question.Hide();
break;
}
}
编辑:改变代码以摆脱讨厌的GOTO声明。
答案 1 :(得分:0)
我建议提取方法,而不是将所有内容都塞进单个Button_Start_Click
中:
private Boolean IsPlayerValid(Player player) {
if (null == player)
return false;
if (String.Equals("N/A", player.Name, StringComparison.OrdinalIgnoreCase)) {
Label_Question.Text = "Please set your name!";
return false;
}
//TODO: you may want add up conditions here
return true;
}
private void Button_Start_Click(object sender, EventArgs e) {
Player player = new Player() {
player.Name = textBox1.Text // you may want this - assign a player's Name
};
if (!IsPlayerValid(player))
return;
Label_Question.Hide();
// Quiz Start
}