1

鉴于这些 C# 类(由 WCF 生成,我无法更改这些):

public SysState GetSysState();

public class SysState { /* nothing much here */}
public class Normal : SysState { /* properties & methods */  }
public class Foobar : SysState { /* different properties & methods */  }

我的代码(当前):

SysState result = GetSysState();

if (result is Normal) HandleNormal((Normal) result);

if (result is Foobar) HandleFoobar((Foobar) result);

我的问题:我一直觉得我遗漏了一些明显的东西,我不需要明确检查类型。我有高级的时刻吗?

4

2 回答 2

1

使用虚拟方法。将您的代码放在它们操作的类中,而不是放在一些获取该类引用的代码中。

public class SysState {
  /* nothing much here, except...: */
  public abstract virtual void DoSomething();
}

public class Normal : SysState {
  /* properties & methods */
  public override void DoSomething()
  {
    // ...
  }
}

public class Foobar : SysState {
  /* different properties & methods */
  public override void DoSomething()
  {
    // ...
  }
}

SysState result = SomeFunctionThatReturnsObjectDerivedFromSysState();

result.DoSomething();

这将执行派生类的 DoSomething 方法。这被称为多态性,是继承的最自然的(而且有些人认为是唯一正确的)使用。

请注意,SysState.DoSomething 不必是抽象的才能工作,但它必须是虚拟的。

于 2010-08-07T20:02:37.060 回答
0

您可以尝试在两者中组合、handleX放置和覆盖它并执行特定任务。它可能不是完美的解决方案,但看起来相对整洁。如果您需要从其他来源输入数据,请将它们作为参数传递?HandleSysStateNormalFoobar

public class SysState
{
    public bool Process(Information info)
    {
        return ( info.Good );
    }
}

public class Normal
{
    public bool Process(Information info)
    {
        return doStuff();
    }
}

public class Foobar
{
    public bool Process(Information info)
    {
        return diePainfully();
    }
}

显然只是一个例子,不知道 HandleNormal 和 HandleFoobar 做什么,但它可以很好地工作。

于 2010-08-07T19:52:41.853 回答