在我的表格顶部,我有:
public static int hoursInt;
public static int minutesInt;
public static int secondsInt;
public static int CompletedIn24;
然后再往下我有以下内容在选择新跑步者时将numericUpDown
框重置为零:
private void lstRunners_SelectedIndexChanged(object sender, EventArgs e)
{
Runner selectedRunner = (Runner)lstRunners.SelectedItem;
numericUpDown1.Value = 0;
numericUpDown2.Value = 0;
numericUpDown3.Value = 0;
}
然后在Finish
按钮点击事件中我有:
hoursInt = Convert.ToInt32(numericUpDown1.Value);
minutesInt = Convert.ToInt32(numericUpDown2.Value);
secondsInt = Convert.ToInt32(numericUpDown3.Value);
if (lstRunners.SelectedIndex > -1 && hoursInt + minutesInt + secondsInt != 0)
{
// Obtain selected climber
Runner selectedRunner = (Runner)lstRunners.SelectedItem;
selectedRunner.Hours = hoursInt;
selectedRunner.Minutes = minutesInt;
selectedRunner.Seconds = secondsInt;
var expertRunner = selectedRunner as Expert;
if (expertRunner != null)
{
expertRunner.UponFinish();
}
以下是Expert : Runner
中的覆盖方法:
public override void UponFinish()
{
base.UponFinish();
// The integer must increment by one if the time is 24:00:00 or less i.e. 23:59:59 would increment the integer as well
if (Hours < 24 || (Hours == 24 && Minutes == 0 && Seconds == 0))
{
CompletedIn24++;
}
}
目前UponFinish()
中的Runner
方法在括号内没有任何内容,因为我不确定是否需要任何内容?
我尝试将CompletedIn24
整数输出到字符串,以查看单击按钮时它是否有效,但即使选择了专家运动员且时间为24:00:00,该值也保持为零或更少。整数没有递增,我不确定导致问题的原因是什么?
任何帮助都将不胜感激。
答案 0 :(得分:1)
只需使用as
关键字,如下所示:
var runner = selectedRunner as Expert;
if(runner != null) runner.UponFinish();
如果您的类Runner
已经定义了一个名为UponFinish
的方法,那么您应该将此方法定义为virtual
并在派生类中重写该方法,如下所示:
public class Runner {
public virtual void UponFinish(){
//...
}
}
public class Expert : Runner {
public override void UponFinish(){
//You talked about the time, I asked for clarification on this
//but it's still very unclear. I suppose when you mean the time is 24:00:00
//that means the hours is 24, the minutes is 0 and the seconds is 0
if(Hours < 24 || (Minutes == 0 && Seconds == 0)) Completedin24++;
}
}
然后当然你不需要任何演员表,只需调用UponFinish
并且正确调用被覆盖的代码(如果有的话):
selectedRunner.UponFinish();
答案 1 :(得分:0)
你可以检查这样的类型:
if (selectedRunner.GetType() == typeof(Expert))
{
Expert expert = (Expert)selectedRunner;
}
答案 2 :(得分:0)
你可以做到
if(selectedRunner is Expert)
{
UponFinish((Expert)selectedRunner);
//or ((Expert)selectedRunner).UponFinish(); if that was the intention
}
或者
Expert selectedExpert = selectedRunner as Expert;
if(selectedExpert != null)
UponFinish(selectedExpert);
编辑:
如果您的UponFinish
功能已经同时属于Runner
和Expert
(即在Expert
中覆盖),则无需在调用之前投射selectedRunner它
答案 3 :(得分:0)
有几种方法可以做到这一点,例如运算符is
:
Operator IS
答案 4 :(得分:0)
您可以使用is关键字检查您的Runner是否是ExpertRunner:
if(selectedRunner is ExpertRunner)
但是,就OOP而言,你不应该这样做,你可能想要检查你的层次结构或逻辑,为什么你需要单独处理这个案例而不是被覆盖的行为(函数或属性)。
答案 5 :(得分:0)
试试这个:
if(lstRunners.SelectedItem is Expert)
{
Expert selectedRunner = lstRunners.SelectedItem as Expert;
selectedRunner.UponFinish();
}
答案 6 :(得分:0)
if (lstRunners.SelectedItem is Expert)
{
((Expert)lstRunners.SelectedItem).UponFinish();
}