为什么我的子类需要用默认参数覆盖?
Why is my subclass required to override with default parameters?
我有一个 subclass,它覆盖了基础 class 中的一个方法。 base class 的方法有默认参数。我的 subclass 需要在重写方法中显示这些默认参数,尽管它们不需要可选。
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()
时允许它使用默认参数。
为什么 subclass 的方法需要一个参数?
I would expect it to accept a parameterless method signature, and then for it to be allowed to use the default parameter when base.MyMethod() is called.
您的期望不正确。为参数添加默认值并不意味着存在没有参数的方法。它只是 将默认值注入 到任何调用代码中。所以没有没有参数的方法可以覆盖。
您可以在基 class:
中显式创建两个重载
protected virtual void MyMethod()
{
MyMethod(1);
}
protected virtual void MyMethod(int parameter)
{
Console.WriteLine(parameter);
}
那么您可以重载任何一个重载,但您的问题并不清楚这是否合适。
我有一个 subclass,它覆盖了基础 class 中的一个方法。 base class 的方法有默认参数。我的 subclass 需要在重写方法中显示这些默认参数,尽管它们不需要可选。
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()
时允许它使用默认参数。
为什么 subclass 的方法需要一个参数?
I would expect it to accept a parameterless method signature, and then for it to be allowed to use the default parameter when base.MyMethod() is called.
您的期望不正确。为参数添加默认值并不意味着存在没有参数的方法。它只是 将默认值注入 到任何调用代码中。所以没有没有参数的方法可以覆盖。
您可以在基 class:
中显式创建两个重载protected virtual void MyMethod()
{
MyMethod(1);
}
protected virtual void MyMethod(int parameter)
{
Console.WriteLine(parameter);
}
那么您可以重载任何一个重载,但您的问题并不清楚这是否合适。