문제

In C++, we can do this(pseudo-code):

class A {
    public:
    virtual void a(A a)=0;
    }

class B : A {
    public:
    virtual void a(B b);
}

But when I write the equivalent in C#:

public abstract class A
{
public virtual void a(A a){}
}

public class B : A
{
public override void a(B b){}
}

the compiler gives an error that says B.a doesn't override A.a. Why doesn't C# allow this? It is very resonable to allow this practise because it obeys the principles of polymorphism.

도움이 되었습니까?

해결책

The C++ version of the code doesn't override the method either. But because C++ doesn't have an override keyword¹, you don't get an error for that because the compiler doesn't know you meant to override the method.

If you want the same behavior in C# as you get in C++, you can just remove the override keyword and replace it with new.

¹ It does in C++11, but I'm assuming you didn't use that or else you would have gotten an error.

It is very resonable to allow this practise because it obeys the principles of polymorphism.

No, it doesn't. Consider this:

A a = new B();
a.a(new A());

If B.a overrode A.a, the above code would call B.a with the argument new A(). But B.b takes an argument of type B, so that would not work.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top