将派生类永久转换为基类

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:

  1. ItemA.GetType() 不返回变量ItemA 的编译时类型——它返回运行时类型ItemA 引用的对象.
  2. 您无法使 (A)B 导致表示更改转换(即新的 A 对象),因为用户定义的转换运算符(您唯一的希望在这里)不能从派生类转换为基类.您将获得正常、安全的参考转换.
  1. ItemA.GetType() does not return the compile-time type of the variable ItemA - it returns the run-time type of the object referred to by ItemA.
  2. There's no way you could make (A)B result in a representation-changing conversion (i.e. a new A 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.

这篇关于将派生类永久转换为基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)