Evo*_*lor 4 c# inheritance overriding compiler-errors default-parameters
我有一个子类,它覆盖了基类中的方法.基类的方法有默认参数.我的子类需要在重写的方法中显示这些默认参数,尽管它们不需要是可选的.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我将方法签名更改为
protected override void MyMethod(int parameter = 1)
Run Code Online (Sandbox Code Playgroud)
甚至
protected override void MyMethod(int parameter)
Run Code Online (Sandbox Code Playgroud)
那很开心 我希望它接受无参数方法签名,然后在base.MyMethod()调用时允许它使用默认参数.
为什么子类的方法需要参数?
我希望它接受无参数方法签名,然后在调用base.MyMethod()时允许它使用默认参数.
你的期望是不正确的.添加参数的默认值并不意味着存在不带参数的方法.它只是将默认值注入任何调用代码.所以没有没有参数可以覆盖的方法.
您可以在基类中显式创建两个重载:
protected virtual void MyMethod()
{
MyMethod(1);
}
protected virtual void MyMethod(int parameter)
{
Console.WriteLine(parameter);
}
Run Code Online (Sandbox Code Playgroud)
然后你可以覆盖过载,但是你的问题不清楚是否合适.