永久投派生类基地 [英] Permanently cast derived class to base
问题描述
Class A { }
Class B : A { }
B ItemB = new B();
A ItemA = (A)B;
Console.WriteLine(ItemA.GetType().FullName);
是否有可能做这样的事情上面,并让编译器打印出A型,而不是B型基本上是有可能永久对象转换,因此失去的所有导出数据?
Is it possible to do something like above and have the compiler print out type A instead of type B. Basically, is it possible to permanently cast an object so it "loses" all the derived data?
推荐答案
你问什么是不可能的,原因有二:
What you ask for is impossible for two reasons:
-
ItemA.GetType()
不返回变量的编译时类型意达
- 它返回运行时类型的对象的在意达
简称的。 - 有没有办法可以让
(一)乙
结果在重新presentation变化的转化率(即一个新的A
)对象,因为用户定义的转换操作符(在这里)你唯一的希望不能来源于立足类转换。你只是要得到一个正常的,安全的,参考的转换。
ItemA.GetType()
does not return the compile-time type of the variableItemA
- it returns the run-time type of the object referred to byItemA
.- There's no way you could make
(A)B
result in a representation-changing conversion (i.e. a newA
object) because user-defined conversion operators (your only hope here) cannot convert from derived to base-classes. You're just going to get a normal, safe, reference-conversion.
这一边,你问什么是很奇怪的;人们会认为你想真的很难违反里氏的substiution原则。目前几乎可以肯定一个严重的设计缺陷在这里,你应该解决的问题。
That aside, what you ask for is very strange; one would think you're trying really hard to violate Liskov's substiution principle. There's almost certainly a serious design-flaw here that you should address.
如果您仍然想做到这一点;可以编写手动构造方法的 A
从 B
通过newing了一个 A
键,然后在复制数据。这可能存在一个的ToA()
在实例方法 B
。
If you still want to do this; you could write a method that manually constructs an A
from a B
by newing up an A
and then copying data over. This might exist as a ToA()
instance-method on B
.
如果你将这个问题,我如何构建一个从现有的 A ?,这让很多更有意义:创建 A拷贝构造函数
,其声明如下公开发行A(A一){...}
,这是不可知的子类的具体细节。这给你一个通用方法来创建一个 A
从 A
或它的一个子类的现有实例。
If you characterized this problem as "How do I construct an A from an existing A?", it makes a lot more sense: create a copy-constructor on A
, whose declaration looks like public A(A a){...}
, which is agnostic to subclass-specific details. This gives you a general means to create an A
from an existing instance of A
or one of it's subclasses.
这篇关于永久投派生类基地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!