在C#中创建派生类时,是否可以用n参数函数覆盖0参数虚函数?
我查看了 MSDN 和其他几个网站,但我仍然没有当然我得到了答案。如果您有一个带有虚函数 Init() 的父类,那么我可以在派生类中拥有一个重写函数 Init(int num) 还是只需为您创建的每个派生类创建一个新函数?如果我没记错的话,后者会导致您在 Child 类中拥有 2 个 Init 函数,对吧?这就是我的意思:
public class Parent {
protected int a;
public Parent() {
a=1;
}
public virtual void Init() {
}
}
public class Child : Parent {
public Child() {
}
//is this allowed?
public override void Init(int multiplier) {
}
//or do i have to do this and have 2 Init functions?
public void Init(int multiplier) {
}
}
I checked out MSDN and a couple other sites but I'm still not sure I got an answer for this. If you have a Parent class with a virtual function Init(), can I then--in the derived class--have an override function Init(int num) or do you simply have to create a new function for each derived class you make? If I'm not mistake, the latter would cause you to have 2 Init functions in the Child class, right? Here's sort of what I mean:
public class Parent {
protected int a;
public Parent() {
a=1;
}
public virtual void Init() {
}
}
public class Child : Parent {
public Child() {
}
//is this allowed?
public override void Init(int multiplier) {
}
//or do i have to do this and have 2 Init functions?
public void Init(int multiplier) {
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您实际上并没有重写该方法,您只是定义了一个新的重载。
为了能够重写方法,基方法必须声明为
public
(或protected
)virtual
(或abstract) 方法和您的派生类必须使用完全相同的签名。
在您的情况下,基类中不存在具有该签名的可重写方法,因此不允许这样做。如果存在带有签名
Init(int)
的可重写方法,则允许这样做,但不存在,编译器将在此处产生错误。You're not actually overriding the method, you're simply defining a new overload.
To be able to override a method, the base method must be declared a
public
(orprotected
)virtual
(orabstract
) method and your derived class must use the same exact signature.In your case, no overridable method with that signature exists in the base class so it is not allowed. It would be allowed if an overridable method existed with the signature
Init(int)
but there isn't, the compiler would yield an error here.这是不可能的。
如果从基类调用它,参数是什么?
This is not possible.
What would the parameter be if it's called from the base class?
覆盖需要具有相同的签名,否则将其设为虚拟是没有意义的。
An override needs to have the same signature, otherwise there is no point in making it virtual.
这不是覆盖。
由于您正在引入新的乘数,因此它将被视为新方法。
但是如果你这样做。
它将被覆盖。
但是,如果您在派生类中执行此操作,则会被视为重载。
This is not an override.
Since you are introducing new multiplier it would be considered new method.
However if you do this.
It will be override.
However if you do this in derived class it will be considered overload.
编译器会给你一个错误,因为“没有什么可以覆盖的”。
基本上,重写的方法必须与基础签名匹配:
http://msdn.microsoft。 com/en-us/library/ms173153.aspx
The compiler will give you an error, because "there is nothing to override".
Basically, the overridden method must match the underlying signature:
http://msdn.microsoft.com/en-us/library/ms173153.aspx