是否可以在C#中更改对象类型 [英] Is it possible to change an object type in C#

查看:67
本文介绍了是否可以在C#中更改对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了满足客户要求,我遇到了一些问题.

I am having some problem in order to meet a client request.

我将尝试使示例非常简单,仅给出问题的思路,并希望提出解决方案.

I will try to keep the example very simple just give an idea of the problem and hopefully come up with a solution.

例如,这时我们有一个"Shape"类,并且形状具有一些特殊性,可以是正方形,三角形等.

At this point we have a class "Shape" for example, and shape has some specializations, it can be square, triangle etc.

到目前为止,一切都很好.

so far so good, everything working great.

现在由于某种原因,我的客户希望将系统中已经存在的正方形更改为三角形,但要保留所有数据的形状.

Now for some reason my client wants to change a square that already exist in the system into a triangle but keep all the data from shape.

有可能吗?有什么解决方法吗?

is that possible? any workarounds for that?

推荐答案

您不能更改对象的运行时类型.只需创建一个新的三角形,复制所有相关值,然后丢弃该正方形即可.如果正方形已经被许多其他对象引用,那么这当然可能会变得棘手,因为您将不得不更新所有引用.

You can not change the runtime type of an object. Just create a new triangle, copy over all the relevant values and throw away the square. This may of course become tricky if the square is already referenced by a lot of other objects because you will have to update all references.

如果不能替换对象,则可能必须提出一个通用的形状类,该类可以用作任何形状.例如,此类可以是一个具体的形状类别的实例周围的薄包装纸.这样一来,您就可以用新的三角形替换包裹的正方形,而外界可以保留对包裹器类的所有引用.

If replacing the object is not an option, you will probably have to come up with a generic shape class that can act as any kind of shape. This class could, for example, be a thin wrapper around an instance of one of the concrete shape classes. This enables you to just replace the wrapped square with a new triangle while the outside world can keep all the references to the wrapper class.

这篇关于是否可以在C#中更改对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆