class A
{
virtual void X() { Console.WriteLine("x"); }
}
class B : A
{
override void X() { Console.WriteLine("y"); }
}
class Program
{
static void Main()
{
A b = new B();
// Call A.X somehow, not B.X...
}
Using the C# language constructs, you cannot explicitly call the base function from 在外面 the scope of A or B. If you really need to do that, then there is a flaw in your design - i.e. that function shouldn't be virtual to begin with, or part of the base function should be extracted to a separate non-virtual function.
You can from 在里面 B.X however call A.X
class B : A
{
override void X() {
base.X();
Console.WriteLine("y");
}
}
但那是另一回事。
正如 Sasha Truf 在 这个答案中指出的,你可以通过 IL 来完成。
正如 mhand 在评论中指出的那样,您也可以通过反射来完成它。
I konow it's history question now. But for other googlers: you could write something like this. But this requires change in base class what makes it useless with external libraries.
class A
{
void protoX() { Console.WriteLine("x"); }
virtual void X() { protoX(); }
}
class B : A
{
override void X() { Console.WriteLine("y"); }
}
class Program
{
static void Main()
{
A b = new B();
// Call A.X somehow, not B.X...
b.protoX();
}
It's impossible if the method is declared in the derived class as overrides. to do that, the method in the derived class should be declared as new:
public class Base {
public virtual string X() {
return "Base";
}
}
public class Derived1 : Base
{
public new string X()
{
return "Derived 1";
}
}
public class Derived2 : Base
{
public override string X() {
return "Derived 2";
}
}
Derived1 a = new Derived1();
Base b = new Derived1();
Base c = new Derived2();
a.X(); // returns Derived 1
b.X(); // returns Base
c.X(); // returns Derived 2