4

我经常使用以下方法将对象链接到它们的父对象:

 Video parent;

有时我的对象可以是不同对象类型的子对象,我也是:

 int parentType;
 Video parentVideo; // if parent == VIDEO then this will be used
 Audio parentAudio; // if parent == AUDIO then this will be used

有没有更好的办法?如何使用可以是不同类型实例的变量?

编辑:当然,如果视频和音频从同一个基类(例如媒体)继承,我可以这样做:

 Media parent;

但是如果父母不是从同一个基类继承呢?

4

4 回答 4

8

我假设您问题中的类型是密封的。在这种情况下,我只会在出路时使用object parent和使用。as(与检查标志相比,使用as可能对性能产生更高的影响,但是......在我所做的任何事情中都不是问题,它也可以很好地用于 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# 中所有其他类型的联合:-)

于 2010-07-21T23:18:54.087 回答
7

好吧,通常一个公开所有功能的接口是合适的,这可以是你的类型。否则(或以及)您可以考虑泛型:

像这样:

class Something<TMediaType>
    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
}
于 2010-07-21T23:14:46.280 回答
3

试着扭转局面……这更有意义吗?

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();
}
于 2010-07-21T23:46:48.123 回答
1

如果没有派生它们的基类 Media,但有可以同样适用于音频或视频内容的通用功能,那么您可以创建一个新的 MediaContainer 类,该类接受对象内容并根据具体情况执行不同的操作内容类型。这样做的目的是将丑陋的“切换”功能封装到一个包装器中,这样您就可以编写依赖于 MediaContainer 的代码,而不必担心它包含的特定媒体或它如何处理委派调用的丑陋工作。

于 2010-07-21T23:30:55.330 回答