超级型,功能灵活

时间:2012-01-01 08:58:01

标签: c# oop object interface

我该如何实现:

  • 我有3种类型(实际上是接口):A,B和C
  • A没有方法,但B和C有一些方法。
  • 我希望在某些情况下类型A可以转换为类型B并使用B方法,在其他情况下可以转换为类型C并使用其方法吗?

1 个答案:

答案 0 :(得分:1)

class Program
{
    interface A { }
    interface B :A { void b(); } // B inherits from A
    interface C :A { void c(); } // C also inherits from A

    static void Main()
    {
      // declare vars

      A a = null;
      B b = null;
      C c = null;

      // a can happily hold references for B.
      a = b;

      // To call B's methods you need to cast it to B.
      ((B)a).b();


      // a can happily hold references for C.
      a = c;

      // To call C's methods you need to cast it to C.

      a = c;
      ((C)a).c(); 
    }
}

来自您的评论

class Program
  {
    private interface A { }
    private interface B : A { string b();}
    private interface C : A { string c();}
    class BClass : B { public string b() { return "B"; } }
    class CClass : C { public string c() { return "C"; } }

    private static void Main()
    {
      A a = null;
      B b = new BClass();
      C c = new CClass();
      a = b;
      ((B)a).b();
      a = c;
      ((C)a).c();
    }    
  }