问题描述
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()
不返回变量ItemA
的编译时类型——它返回运行时类型ItemA
引用的对象.- 您无法使
(A)B
导致表示更改转换(即新的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.
除此之外,你的要求很奇怪;有人会认为您非常努力地违反 Liskov 的替代原则.几乎可以肯定,这里有一个严重的设计缺陷需要解决.
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
手动构造 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
,其声明类似于 public 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 its subclasses.
这篇关于将派生类永久转换为基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!