将接口类型转换为实现类

时间:2016-10-07 19:09:48

标签: design-patterns interface casting

我的问题涉及我提供的以下示例。我觉得这是一种反模式。不确定它是否有名字。我想要的是能够访问特定的实现。试图避免回答可能仅仅是对这种模式是坏/好的意见,我想知道一种更好的方式来重新考虑这个问题,并且如果有这个(反)模式的名称。

interface WTF
{
  Type type;
}

enum Type
{
  A,
  B
}

interface A : WTF
{
  Type type = Type.A;

  void MethodA();
}

interface B : WTF
{
  Type type = Type.B;

  void MethodB();
}



void Foo(List<WTF> list)
{
  foreach(var i in list)
  {
    switch(i.type)
    {
      case Type.A:
        A a = (A)i;
        a.MethodA();
        break;
      case Type.B:
        B b = (B)i;
        b.MethodB();
        break;
    }
  }
}

1 个答案:

答案 0 :(得分:0)

为什么你必须给它一个不同的名字?在这种情况下,这种最佳方式是这样的:

interface WTF
{
  Type type;
  void Method();
}

enum Type

interface A : WTF
{

}

interface B : WTF
{


}
void Foo(List<WTF> list)
{
  foreach(var i in list)
  {
    i.Method();
  }
}
相关问题