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()不返回变量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)Bresult in a representation-changing conversion (i.e. a newAobject) 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.
这篇关于将派生类永久转换为基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将派生类永久转换为基类
基础教程推荐
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
