如何用强制转换替换类的实例,同时对它的所有引用仍然有效
假设我有很多“Item”实例。 后来,我想将其中一些更改为扩展“Item”的“SpecialItem”。
我可以用 SpecialItem 的实例替换 Item 的实例,而不必更新对旧 Item 实例的所有现有引用吗?
...所以我想做 this = this 作为 SpecialItem 但当然,你不能用“this”来做到这一点;)
Let's say I have many instances of 'Item'.
Later, I want to change some of them to 'SpecialItem' which extends 'Item'.
Can I replace the instance of Item by an Instance of SpecialItem, without having to update all existing references to the old instance of Item?
...So i'd like to do
this = this as SpecialItem
But ofcourse, you can't do that with 'this' ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只能向后投射,或“向上”继承链。例如:
如果您需要更高级的运行时交换功能,请考虑使用组合而不是继承,例如,将您的项目引用为接口实例而不是类实例。
但是,正如 @IronBCC 所说,如果您只是想交换属性,则可以通过将属性公开来实现。
You can only cast backwards, or 'up' the inheritance chain. Something like:
If you need more advanced runtime swapping abilities, think about using composition instead of inheritance, eg, referencing your items as Interfaces instances instead of Class instances.
However, as @IronBCC says, if you are just looking to swap properties, you can do so by making the property public.
不,你不能这样做。
但是您可以使用这样的构造:
和 user link.link 来获取您的 Item,并使用 link.link = new SpecialItem() 来设置新值。
No, your can't do this.
But you may use such construction:
and user link.link, to get your Item, and link.link = new SpecialItem(), to set new value.