使用继承可选参数基本方法的模糊性 [英] Ambiguity with inheriting an optional-parameter base method
问题描述
我有一个基类有一个可选的默认参数,子类自动提供一个值:
I have a base class with one optional default parameter, which a child class automatically provides a value for:
public class Merchant
{
public string WriteResults(List<string> moreFields = null)
{
List<string> ListOfObjects = new List<string>() {Name, Address};
if (moreFields != null)
{
ListOfObjects.AddRange(moreFields);
}
return ListOfObjects.ToString() //not real output
}
public class SpecificMerchant : Merchant
{
new public string WriteResults()
{
return ((Merchant)this).WriteResults(new List<string>() {
Address, Phone //class-specific parameters
});
}
}
我使用 / code>关键字当调用
SpecificMerchant.WriteResults
时,因为父和基本可以不带参数,但编译器说这是不必要的:
I used the new
keyword when calling SpecificMerchant.WriteResults
because both the parent and the base can take no parameters, but the compiler says this is unnecessary:
成员'SpecificMerchant.WriteResults()'不隐藏
继承的成员。不需要新的关键字。
The member 'SpecificMerchant.WriteResults()' does not hide an inherited member. The new keyword is not required.
为什么?
推荐答案
因为可选参数是编译时构造,而不是运行时
Because optional parameters are a compile time construct, not a runtime construct.
你的基类总是有一个参数的方法。如果你调用没有参数的方法,编译器只是在编译时替换null 。
Your base class is always going to have a method with one parameter. The compiler just "substitutes" null at compile time if you call that method without an argument.
做你正在实施的上面。即使你删除了 new
关键字,这将让它编译,你添加了很多困惑。如果需要,我可以使基类实现为virtual,或者向基类中添加两个方法,而不是使用可选的参数。
That being said, I would avoid trying to do what you're implementing above. Even if you remove the new
keyword, which will let it compile, you're adding a lot of confusion. I would, personally, make the base class implementation virtual, if required, or add two methods to the base class and override one instead of using optional arguments.
资源,我建议阅读 James Michael Hare关于可选参数的帖子 - 他讨论了这个陷阱,当你将可选参数与继承混合时。
For a good resource, I'd recommend reading James Michael Hare's post on Optional Parameters - He discusses the pitfalls, like this one, when you mix optional arguments with inheritance.
这篇关于使用继承可选参数基本方法的模糊性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!