你怎么用,可以是多种类型的变量工作? [英] How do you work with a variable that can be of multiple types?
问题描述
我经常使用对象链接到他们的父母:
I frequently link objects to their parents using:
Video parent;
有时候,我有对象可以是不同的对象类型的孩子,所以做我:
Sometimes I have objects that can be children of different object types, so do I:
int parentType;
Video parentVideo; // if parent == VIDEO then this will be used
Audio parentAudio; // if parent == AUDIO then this will be used
有没有更好的办法?
我如何与可以是不同类型的实例变量工作
Is there a better way? How do I work with a variable that can be an instance of different types?
编辑:当然,如果视频和从相同的基类(如媒体),我能做到这一点音频继承:
Of course, if Video and Audio inherit from the same baseclass (eg. Media) I could do this:
Media parent;
但是,如果家长不从同一个基类继承?
But what if the parents do not inherit from the same baseclass?
推荐答案
我假设你的问题的类型进行密封。在这种情况下,我只想用对象父
,并使用为
的出路。 (使用为
可以拥有比检查一个标志一个更高的性能影响,但......不是在任何一个问题我已经做了,它也可以在一个空值很好地被使用门卫)
I am assuming that the types in your question are sealed. In which case I would just use object parent
and use as
on the way out. (Using as
can have a higher performance impact than checking a flag, but... not a concern in anything I have done and it can also be nicely used in a null-guard.)
Video video = null;
if ((video = parent as Video) != null) {
// know we have a (non-null) Video object here, yay!
} else if (...) {
// maybe there is the Audio here
}
以上实际上只是在一个不受约束的识别联合编写一次性-模式匹配的一个愚蠢的C#的方式(对象是在C#中所有其他类型的工会: - )
The above is actually just a silly C# way of writing a one-off-pattern-match on an unconstrained discriminated union (object is the union of every other type in C# :-)
这篇关于你怎么用,可以是多种类型的变量工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!