C# 如何覆盖基类方法并添加参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/633336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to override a Base Class method and add a parameter
提问by user72603
I have this in my base class:
我的基类中有这个:
protected abstract XmlDocument CreateRequestXML();
I try to override this in my derived class:
我尝试在我的派生类中覆盖它:
protected override XmlDocument CreateRequestXML(int somevalue)
{
...rest of code
}
I know this is an easy question but because I've introduced a param is that the issue? The thing is, some of the derived classes may or may not have params in its implementation.
我知道这是一个简单的问题,但是因为我引入了一个参数,所以是这个问题吗?问题是,某些派生类在其实现中可能有也可能没有参数。
采纳答案by JaredPar
When you override a method, with the exception of the word override in place of virtual or abstract, it must have the exact same signature as the original method.
当你重写一个方法时,除了用 override 这个词代替 virtual 或 abstract 之外,它必须与原始方法具有完全相同的签名。
What you've done here is create a new unrelated method. It is not possible to introduce a parameter and still override.
你在这里所做的是创建一个新的不相关的方法。不可能引入参数并仍然覆盖。
回答by John Rasch
Yes the parameter is the issue, the method signature must match exactly (that includes return value and parameters).
是的参数是问题,方法签名必须完全匹配(包括返回值和参数)。
回答by Steve Rowe
If some of the derived classes need paramters and some do not, you need to have two overloaded versions of the method. Then each derived class can override the one it needs.
如果某些派生类需要参数而有些不需要,则您需要有该方法的两个重载版本。然后每个派生类都可以覆盖它需要的那个。
class Foo {
protected abstract XmlDocument CreateRequestXML(int somevalue);
protected abstract XmlDocument CreateRequestXML();
};
class Bar : public Foo {
protected override XmlDocument CreateRequestXML(int somevalue) { ... };
protected override XmlDocument CreateRequestXML()
{ CreateRequestXML(defaultInt); }
};
This of course introduces a problem of the user calling the wrong one. If there is no acceptable default for the extra paramter, you may have to throw an exception in the derived class if the wrong version is called.
这当然引入了用户调用错误的问题。如果额外参数没有可接受的默认值,则在调用错误版本时可能必须在派生类中抛出异常。
回答by Patrick Peters
I am very curious what you are trying to accomplish with this code.
我很好奇你想用这段代码完成什么。
Normally you define an abstract function when a usage class knows its signature. The usage class has a "contract" with you base class.
通常,当使用类知道其签名时,您定义抽象函数。用法类与您的基类有“合同”。
When you want to derive from the baseclass and add additional parameters, how does the usage class know what to call on the base class anyway?
当您想从基类派生并添加其他参数时,使用类如何知道在基类上调用什么?
It looks like an architectual flaw....but maybe you can add some extra information to the inital topic.
它看起来像一个架构缺陷......但也许你可以在初始主题中添加一些额外的信息。