[英]can I typecast one subclass to other subclass object in C#
I want to type cast a below: 我想在下面输入一个:
Class A
{
}
Class B : A
{
}
Class C: A
{
}
Class D{
B b = new b();
C c = (C) b;
}
Please suggest how can I type cast class C to Class B 请建议如何将类C转换为B类
No, that's not possible since B is not a C, so this cast must fail. 不,那是不可能的,因为B 不是 C,所以这个演员必须失败。 One workaround would be to implement a custom explicit conversion operator but otherwise there is no way - you can only cast to a more specific type (downcast) or to a base class (upcast) in the same inheritance tree.
一种解决方法是实现自定义显式转换运算符,否则无法实现 - 您只能在同一继承树中转换为更具体的类型(向下转换)或基类(向上转换)。
You can not. 你不能。 What you can is cast B to A.
你可以把B投到A.
It's simply impossible. 这根本不可能。 You can't to such conversion.
你不能这样的转换。
In fact they have same base class, but they aren't same. 实际上它们具有相同的基类,但它们并不相同。 For example, take a look at this.
例如,看看这个。
Triangle
is Shape
and Rectangle
is Shape
Triangle
是Shape
, Rectangle
是Shape
But you can't convert Triangle
to Rectangle
, because they are different. 但是你不能将
Triangle
转换为Rectangle
,因为它们是不同的。
No, you can't. 不,你不能。 If you want to copy properties from one class to another, you might consider AutoMapper .
如果要将属性从一个类复制到另一个类,可以考虑使用AutoMapper 。
Not possible. 不可能。 Classes C and B are not related in the class hierachy.
类C和B在类层次中不相关。
Animal
{
}
Giraffe : Animal
{
}
Shark : Animal
{
}
Your question is how do you turn a Giraffe into a Shark. 你的问题是你如何将长颈鹿变成鲨鱼。 Unfortunately, it can't be done.
不幸的是,它无法完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.