我的表单上有一个Get Status
按钮,目前的代码如下所示:
private void btnGetStatus_Click(object sender, EventArgs e)
{
// Check if a runner has been selected
if (lstRunners.SelectedIndex > -1)
{
// Obtain selected runner
Runner selectedRunner = (Runner)lstRunners.SelectedItem;
// Call the method in Runner class to get the runner's status
selectedRunner.GetStatus(selectedRunner);
}
}
}
}
现在我有Runner
课程:
public void GetStatus(Runner selectedRunner)
{
if (selectedRunner.HasFinished == true)
{
lblRunnerInfo.Text = "Runner has already finished!";
}
}
我基本上要做的是让btnGetStatus
调用GetStatus
类中的Runner
方法,然后我想要的方法就是检查boolean HasFinished
看看跑步者是否已经完成,如果他们已经完成,lblRunnerInfo.Text
有一条消息反映这一点,如果布尔值为假,那么基本上输出一条消息说"跑者有尚未完成/未完成"
我不太确定从类中访问表单控件是否正确,或者是否可以完成,但我不确定如何按照我想要的方式执行此操作(获取) GetStatus
方法检查跑步者的状态,而不是让btnGetStatus
解雇代码。)
答案 0 :(得分:0)
我认为您正在寻找的是:
lblRunnerInfo.Text = selectedRunner.GetStatus();
然后在跑步者班:
public string GetStatus()
{
if (this.HasFinished == true)
{
return "Runner has already finished!";
}
return "Finished";
}
答案 1 :(得分:0)
您可以按如下方式更改btnGetStatus_Click:
private void btnGetStatus_Click(object sender, EventArgs e)
{
// Check if a runner has been selected
if (lstRunners.SelectedIndex > -1)
{
// Obtain selected runner
Runner selectedRunner = (Runner)lstRunners.SelectedItem;
// Call the method in Runner class to get the runner's Status
// CHANGED
if (selectedRunner.HasFinished)
lblRunnerInfo.Text = "Runner has already finished";
}
}
这样,表单处理输出,Runner类负责“运行”。如果您稍后有更复杂的状态,那么您仍然可以为状态添加枚举并检索状态而不是仅检查HasFinished。要检索文本,您需要将Status枚举中的映射添加到相应的文本中。
答案 2 :(得分:0)
为什么不直接访问您的HasFinished()属性?
private void btnGetStatus_Click(object sender, EventArgs e)
{
// Check if a runner has been selected
if (lstRunners.SelectedIndex > -1)
{
// Obtain selected runner
Runner selectedRunner = (Runner)lstRunners.SelectedItem;
// Call the method in Runner class to get the runner's status
if (selectedRunner.HasFinished)
{
lblRunnerInfo.Text = "Runner has already finished!";
}
else
{
lblRunnerInfo.Text = "Runner has NOT finished yet!";
}
}
}
答案 3 :(得分:0)
这样的事情
private void btnGetStatus_Click(object sender, EventArgs e)
{
// Check if a runner has been selected
if (lstRunners.SelectedIndex > -1)
{
// Obtain selected runner
Runner selectedRunner = (Runner)lstRunners.SelectedItem;
// Call the method in Runner class to get the runner's status
lblRunnerInfo.Text = selectedRunner.GetStatus(selectedRunner);
}
}
然后将GetStatus设置为字符串
public string GetStatus(Runner selectedRunner)
{
if (selectedRunner.HasFinished == true)
{
return "Runner has already finished!";
}
}