可能重复:
覆盖方法上的 C# 可选参数
这是以下代码的输出:
Peter: -1
Peter: 0
Fred: 1
Fred: 1
你能解释一下为什么彼得p.TellYourAge()
和彼得的呼唤p.DoSomething()
不一样吗?
这里是自己尝试的代码(VS2010 和 FW 4):
static void Main(string[] args)
{
Peter p = new Peter();
p.TellYourAge(); // expected -1, result: -1
p.DoSomething(); // expected -1, result: 0
Fred f = new Fred();
f.TellYourAge(1); // expected 1, result: 1
f.DoSomething(); // expected 1, result: 1
Console.ReadKey();
}
}
public abstract class Person
{
public abstract void TellYourAge(int age); // abstract method without default value
}
public class Peter : Person
{
public override void TellYourAge(int age = -1) // override with default value
{
Console.WriteLine("Peter: " + age);
}
public void DoSomething()
{
TellYourAge();
}
}
public class Fred : Person
{
public override void TellYourAge(int age) // override without default value
{
Console.WriteLine("Fred: " + age);
}
public void DoSomething()
{
TellYourAge(1);
}
}