为什么允许从超类到子类的隐式转换?

5 .net c# inheritance type-conversion implicit-cast

有人可以告诉我为什么用"// Compiles"编译的行,以及为什么带"//不编译"的行没有?

我不明白为什么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");
 }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

tst*_*ter 15

因为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.
Run Code Online (Sandbox Code Playgroud)


Alf*_*ers 8

让我们将类的名称从AClass更改为Mammal,将BClass更改为Dog.


a = b; // you're putting a dog on a variable of type Mammal. That's OK.
b = a; // You're putting a mammal (could be a cat, a monkey, etc.) on a variable of type Dog.
Run Code Online (Sandbox Code Playgroud)

也许不是最好的例子,但它可能足以让你理解.

  • 不去动物园就不能谈论OOP.=) (7认同)

Bri*_*ian 1

A 不能隐式转换为 B。B 可转换为 A。

foo = bar
Run Code Online (Sandbox Code Playgroud)

它将尝试将“bar”转换为“foo”的类型。

(也就是说,我认为您只是误解了“赋值”在隐式转换方面的工作原理。)