谁能告诉我为什么带有“//Compiles”的行可以编译,而带有“//Doesn't Compile”的行不能编译?
我不明白为什么 A 可以隐式转换为 B,而不是相反。
public class SomeClass {
static public void Test() {
AClass a = new AClass();
BClass b = new BClass();
a = b; // Compiles
b = a; // Doesn't compile
}
}
public class AClass {
public void AMethod() {
Console.WriteLine("AMethod");
}
}
public class BClass : AClass {
public void BMethod() {
Console.WriteLine("BMethod");
}
}
谢谢!
最佳答案
因为 B 做 A 做的所有事情,但 A 不一定做 B 做的所有事情。这样想:
AClass --> Shape
BClass --> Circle
Shape a = new Shape();
Circle b = new Circle();
a = b; // works because a is of type "Shape" and a circle is a specific shape
b = a; // doesn't work because b is of type "Circle" and a could be a square.
关于c# - 为什么允许从父类(super class)到子类的隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1469155/