简体   繁体   English

C#:将超类转换为子类

[英]C#: Convert SuperClass to SubClass

I have a class (SuperClass) which is used. 我有一个使用的类(SuperClass)。 For own purposes I designed a SubClass, which adds aditional information for me. 我出于个人目的设计了一个SubClass,它为我添加了附加信息。

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. 现在我的问题是,在运行时我要将Superclass的实例转换为SubClass的实例。 Do Some operations on it and then back to SuperClass. 对它执行一些操作,然后返回到SuperClass。 So my question ist, how is it possible to actually convert an instance of SueprClass into an instance of SubClass? 所以我的问题学家,实际上如何将SueprClass实例转换为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. 如果您正在使用的实例被初始化为SuperClass ,则无法将其神奇地转换为SubClass的实例-这会使整个类型系统丢在窗外。

You can, however, add a way to convert SuperClass to SubClass , but you'll have to write code for that. 但是,您可以添加一种将SuperClass转换为SubClass ,但是您必须为此编写代码。

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). 一种方法是在SubClass中添加一个构造函数,以接收SuperClass实例以及SubClass需要的任何其他信息(如果不需要其他信息,也许最好使用扩展方法而不是继承)。
Another way would be to write explicit conversion operator. 另一种方法是编写显式转换运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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