你如何使用多种类型的变量?
我经常使用以下方法将对象链接到父母:
Video parent;
有时我的对象可以是不同对象类型的子对象,所以我:
int parentType; Video parentVideo; // if parent == VIDEO then this will be used Audio parentAudio; // if parent == AUDIO then this will be used
有没有更好的办法? 如何使用可以是不同类型实例的变量?
编辑:当然,如果video和音频inheritance自相同的基类(例如媒体),我可以这样做:
Media parent;
但如果父母不inheritance同一个基类怎么办?
我假设您的问题中的类型是密封的。 在这种情况下,我只会使用object parent
并在出路时使用。 (使用as
可以比检查标志具有更高的性能影响,但是…在我做过的任何事情中都没有问题,它也可以很好地用在空值保护中。)
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#中所有其他类型的联合:-)
好吧,通常一个暴露所有function的界面是合适的,这可以是你的类型。 否则(或同样)你可以考虑generics:
像这样:
class Something where TMediaType : IMedia // use this statement to limit the types. It // is not required, if not specified it can be // of any type { TMediaType data; // other such things }
尝试扭转局面……这更有意义吗?
interface IMedia { void Play(); void Stop(); } class Video : IMedia { public Audio Audio; /// aka child public void Play() { } public void Stop() { } } class Audio : IMedia { public Video Video; /// aka parent...questionable unless Audio /// always has a parent Video public void Play() { } public void Stop() { } } private void PlayAnyMedia(IMedia media) /// Write against an interface { media.Play(); }
如果没有他们派生的基类Media,但是有一些通用function可以同样适用于音频或video内容,那么您可以创建一个新的MediaContainer类,它接受对象内容并根据具体情况执行不同的操作。内容类型。 这样做是将丑陋的“切换”function封装到包装器中,这样您就可以编写依赖于MediaContainer的代码而无需担心它包含的特定媒体或它如何处理委派调用的丑陋工作。