c# - 为什么允许从父类(super class)到子类的隐式转换?

标签 c# .net inheritance type-conversion implicit-conversion

谁能告诉我为什么带有“//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/

相关文章:

c# - 是否可以使用 Gdata API C# 将 Windows 表单点击信息发布到 Google Analytics(track id)

c# - GetResponse 抛出 WebException 并且 ex.Response 为空

c# - 并非所有使用 Image.PropertyItems 检索的图像属性

c# - 为什么仅在实现接口(interface)后才重写方法?

c# - 无法转换从通用基础继承的对象

java - 当对象调用其父类(super class)的方法时如何处理对象?

c# - 类的 in 修饰符有什么意义

c# - SqlCommand参数替换

c# - 在 Xamarin 表单的 XAML 中包含按钮时如何修复此异常?

c# - Sys.InvalidOperationException : Handler must be a function