简体   繁体   中英

C#: Convert SuperClass to SubClass

I have a class (SuperClass) which is used. For own purposes I designed a SubClass, which adds aditional information for me.

class SuperClass{
}

class SubClass: SuperClass{
}

Now my problem is, that at runtime I want to convert an instance of Superclass into an instance of SubClass. Do Some operations on it and then back to SuperClass. So my question ist, how is it possible to actually convert an instance of SueprClass into an instance of SubClass?

SubClass newItem = superClass as SubClass;

If the instance you are working with was initialized as SuperClass , you can't magically convert it into an instance of a SubClass - that would throw the entire type system out the window.

You can, however, add a way to convert SuperClass to SubClass , but you'll have to write code for that.

One way is to add a constructor to the SubClass that takes in an instance of the SuperClass and whatever additional information the SubClass needs (if it doesn't need additional information, perhaps you better use extension methods instead of inheritance).
Another way would be to write explicit conversion operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM