考虑以下类:
public class X {};
public class Y : X {};
public class Z : X {};
public class A {
public bool foo (X bar) {
return false;
}
};
public class B : A {
public bool foo (Y bar) {
return true;
}
};
public class C : A {
public bool foo (Z bar) {
return true;
}
};
有没有办法实现下面的期望输出?
A obj1 = new B();
A obj2 = new C();
obj1.foo(new Y()); // This should run class B's implementation and return true
obj1.foo(new Z()); // This should default to class A's implementation and return false
obj2.foo(new Y()); // This should default to class A's implementation and return false
obj2.foo(new Z()); // This should run class C's implementation and return true
我遇到的问题是,无论传递的参数如何,A 类的实现总是被调用。
最佳答案
您需要在 A
类中创建 foo
方法 virtual
以便它可以被正确覆盖并以多态方式调用。
public class A { public virtual bool Foo (X bar) { ... } }
public class B { public override bool Foo (X bar) { ... } }
你目前的做法是在 B
和 C
中有效地定义一个新的方法实现,只有当实例属于该类型时才会被调用.由于您将它们声明为类型 A
(A obj1 = new B();
) 并且该方法不是虚拟的,因此 A
实现将总是被调用。
关于C# 多态性和方法继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30298903/