为什么隐式转换从超类允许继承? [英] Why is implicit conversion allowed from superclass to subclass?

查看:155
本文介绍了为什么隐式转换从超类允许继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我,为什么与行//编译编译,为什么符合//不能编译不?

Can someone tell me why the line with "//Compiles" compiles, and why the line with "//Doesn't Compile" does not?

我不明白为什么会隐式转换为B,不是倒过来。

I don't understand why A would be implicitly convertible to B, not the other way round.

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做出一切一做这一点,但一个不一定做的一切,B做出。想想这样说:

Because B does everything that A does but A does not necessarily do everything that B does. Think of it this way:

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.

这篇关于为什么隐式转换从超类允许继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆