【问题标题】:Casting an interface type to an implementing class将接口类型转换为实现类
【发布时间】:2017-02-16 20:52:13
【问题描述】:

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

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;
    }
  }
}

【问题讨论】:

  • 我可能只是没有在谷歌上搜索正确的词,所以任何可能引导我到那里的帮助都会很高兴
  • 你的例子是错误的。 interface A 中的 Type type = Type.A; 和 interface B 中的 Type type = Type.B; 无效。接口不能有实现。你也不需要类型。
  • 我认为我们只是在挑剔,考虑到我没有提到一种语言,如果它有助于将接口 A 和 B 视为抽象类

标签: design-patterns interface casting


【解决方案1】:

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

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();
  }
}

【讨论】:

  • 所以 methodA 和 methodB 只是一些其他方法的例子,而不是与 WTf 共享的东西
  • 如果你能修改这些类,为什么不给它们一个共享方法呢?
猜你喜欢
  • 2015-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
相关资源
最近更新 更多