C# 重写抽象方法(包括输入参数)
在 C# 中可以做这样的事情
public absctract class ImportBase()
{
public abstract void CreateDocument();
}
public class UsingOne : ImportBase
{
public override bool CreateDocument(string name)
{
return null;
}
}
,我想要一些基类,它只有一些方法,但在派生类中我需要更改输入参数和方法内部。
It is possible in C# do something like this
public absctract class ImportBase()
{
public abstract void CreateDocument();
}
public class UsingOne : ImportBase
{
public override bool CreateDocument(string name)
{
return null;
}
}
I want have some Base class, which only have some methods,but in derived class i need change inputs parameters and inside of method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您没有重写该方法。拥有抽象(或虚拟)方法的要点是,给定任何
ImportBase
,我应该能够调用UsingOne
显然不是这种情况>,因为它需要更多信息。因此,您实际上是在尝试将调用者与UsingOne
联系起来,而不仅仅是ImportBase
- 此时您就失去了多态性的好处。要重写方法,实现基本上必须具有相同的签名。
You're not overriding the method. The point of having an abstract (or virtual) method is that given any
ImportBase
, I should be able to callThat's clearly not the case with
UsingOne
, as it needs more information. So you're really trying to tie your caller toUsingOne
, not justImportBase
- at which point you've lost the benefits of polymorphism.To override a method, the implementation has to have the same signature, basically.
您可能希望最大程度地减少派生类上的重复代码。基本上不可能覆盖不同的签名,但您肯定可以重构代码,在基类中保留可能的重复代码并在派生类上使用它。
您可以创建
UsingOne
实例并调用CreateDocument(string name)
Probably you want to minimize the duplicate code on your derived classes. Basically it's not possible to have an override of a different signature but surely you can refactor your code where you can keep the possible duplicate code in the base class and use it on your derived classes.
You can create instance of
UsingOne
and invokeCreateDocument(string name)
没有。派生类上的签名必须相同。我建议使用构建器模式。
http://en.wikipedia.org/wiki/Builder_pattern
nope. signature must be same on the derived class. i suggest to use builder pattern.
http://en.wikipedia.org/wiki/Builder_pattern