在 C++ 中,我们可以这样做(伪代码):
class A {
public:
virtual void a(A a)=0;
}
class B : A {
public:
virtual void a(B b);
}
但是当我用 C# 编写等价物时:
public abstract class A
{
public virtual void a(A a){}
}
public class B : A
{
public override void a(B b){}
}
编译器报错说 B.a 没有覆盖 A.a。为什么 C# 不允许这样做?允许这种做法是非常合理的,因为它遵守多态性原则。
最佳答案
代码的 C++ 版本也不会覆盖该方法。但是因为 C++ 没有 override
关键字¹,所以您不会收到错误,因为编译器不知道您打算覆盖该方法。
如果您希望在 C# 中获得与在 C++ 中相同的行为,您只需删除 override
关键字并将其替换为 new
。
¹ 它在 C++11 中确实如此,但我假设您没有使用它,否则您会得到一个错误。
It is very resonable to allow this practise because it obeys the principles of polymorphism.
不,它没有。考虑一下:
A a = new B();
a.a(new A());
如果 B.a
覆盖了 A.a
,上面的代码将调用 B.a
并带有参数 new A()
。但是 B.b
需要一个类型为 B
的参数,所以这是行不通的。
关于c# - 在 C++ 中允许的函数在 C# 中不允许?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23145964/