我在下面遇到编译器错误.我不知道为什么我不能引用派生类并将其传递给一个接受基类引用的方法.请注意,方法foo()和bar()不一定具有相同的语义,因此它们应该具有不同的名称,这些方法不是问题.
public class X { public int _x; }
public class Y : X { public int _y; }
public class A {
public void foo( ref X x ) {
x._x = 1;
}
}
public class B : A {
public void bar( ref Y y ) {
foo( ref y ); // generates compiler error
foo( ref (X)y); // wont work either
y._y = 2;
}
}
Run Code Online (Sandbox Code Playgroud)
我找到的唯一解决方案是:
public class B : A {
public void bar( …Run Code Online (Sandbox Code Playgroud) c# ×1