考虑以下类:
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;
}
};
Run Code Online (Sandbox Code Playgroud)
有没有办法实现以下所需的输出?
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
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,无论传递的参数如何,都始终会调用A类的实现.
您需要foo在类中创建该方法,A virtual以便可以正确地重写它并以多态方式调用.
public class A { public virtual bool Foo (X bar) { ... } }
public class B { public override bool Foo (X bar) { ... } }
Run Code Online (Sandbox Code Playgroud)
您目前正在这样做的方式是有效地定义一个新的方法实现,B并且C只有在该实例属于该类型时才会调用它.由于您将它们声明为type A(A obj1 = new B();)并且该方法不是虚拟的,因此A将始终调用实现.