[英]Casting object of inherited class to instance of inheriting type
I have the following code.我有以下代码。
class Program
{
static void Main(string[] args)
{
Outer outer = new Outer();
Inner inner = new Inner();
Outer outer2 = new Inner();
Inner inner2 = new Outer();
}
}
public class Outer { }
public class Inner : Outer { }
I get the compiler error when assigning new Outer()
to inner2
because it's of type Inner
.将
new Outer()
分配给inner2
时出现编译器错误,因为它的类型为Inner
。 I understand that it's to do with the inheritance but I can not figure out why because the contents are the same.我知道这与继承有关,但我不知道为什么,因为内容相同。 Also, how can I force it to be cast to
Inner
.另外,如何强制将其强制转换为
Inner
。
I have tried我试过了
(inner)new Outer();
new Outer() as Inner;
But it threw an exception about conversion in the former and became null in the latter.但它在前者中抛出了一个关于转换的异常,而在后者中变为空。 Not sure what to google for to find out.
不知道要谷歌什么才能找到。 I mean like this but the exact opposite.
我的意思是这样,但恰恰相反。
A subclass is of type base class, but not the opposite.子类是基类类型,但不是相反的。 consider renaming them to
考虑将它们重命名为
class Dog {}
class GermanShepard : Dog {}
This makes it clear that A German Sheppard is definitely a dog.这清楚地表明德国牧羊犬绝对是一只狗。 But a dog is not necessarily a German Shepard.
但狗不一定是德国牧羊犬。
writing the following is not possible, since the new dog could end up being another type of dog.不可能写出以下内容,因为新狗最终可能成为另一种狗。
GermanShepard fred = new Dog(); //error!!
It might be a Shitzu or a Labrador.它可能是一只 Shitzu 或一只拉布拉多犬。 But you can always cast a German Shepard to a dog.
但是你总是可以把德国牧羊犬扔给狗。 Similarly you can always cast a Labrador to a dog.
同样,您始终可以将拉布拉多犬扔给狗。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.