C# 为什么我的子类需要用默认参数覆盖?
我有一个子类重写基类中的方法。基类的方法具有默认参数。我的子类需要在重写的方法中显示这些默认参数,尽管它们不需要进行选项化C# 为什么我的子类需要用默认参数覆盖?,c#,inheritance,compiler-errors,overriding,default-parameters,C#,Inheritance,Compiler Errors,Overriding,Default Parameters,我有一个子类重写基类中的方法。基类的方法具有默认参数。我的子类需要在重写的方法中显示这些默认参数,尽管它们不需要进行选项化 public class BaseClass { protected virtual void MyMethod(int parameter = 1) { Console.WriteLine(parameter); } } public class SubClass : BaseClass { //Compiler erro
public class BaseClass
{
protected virtual void MyMethod(int parameter = 1)
{
Console.WriteLine(parameter);
}
}
public class SubClass : BaseClass
{
//Compiler error on MyMethod, saying that no suitable method is found to override
protected override void MyMethod()
{
base.MyMethod();
}
}
但是,如果我将方法签名更改为
protected override void MyMethod(int parameter = 1)
甚至
protected override void MyMethod(int parameter)
那么它是快乐的。我希望它接受无参数方法签名,然后在调用base.MyMethod()
时允许它使用默认参数
为什么子类的方法需要参数
我希望它接受无参数方法签名,然后在调用base.MyMethod()时允许它使用默认参数
你的期望是错误的。为参数添加默认值并不意味着不存在该参数的方法。它只是将默认值注入任何调用代码中。因此,没有一个方法没有参数可以覆盖
可以在基类中显式创建两个重载:
protected virtual void MyMethod()
{
MyMethod(1);
}
protected virtual void MyMethod(int parameter)
{
Console.WriteLine(parameter);
}
然后,您可以覆盖任意一个重载,但您的问题不清楚这是否合适