2012-01-01 115 views
2

我如何能实现这一点:超级型与灵活的功能

  • 我有3种类型(实际上接口):A,B和C
  • A没有方法,但B和C的一些方法。
  • 我想在某些情况下,A类可转换为类型强制转换为C型,并使用它的方法B和采用B方法,在其他情况呢?
+5

什么你所描述的被认为是糟糕的设计:它违反了[里氏替换原则(HTTP://en.wikipedia。组织/维基/ Liskov_substitution_principle)。 – 2012-01-01 09:07:25

+0

是的,这是一个糟糕的设计。我应该再想一次。谢谢 – Mehrdad 2012-01-01 09:27:21

回答

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

私有接口A {} 私有接口B:A {string b();} 私有接口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} = null; B b = new BClass(); C c = new CClass(); a = b; ((B)a).b(); a = c; ((C)a).c();} – Mehrdad 2012-01-01 09:28:20