2011-10-14 52 views
0

,我有一個接口如何調用在類中實現的接口的方法?

public interface IMethod 
{ 
    String Add(string str); 
    Boolean Update(string str); 
    Boolean Delete(int id); 
} 

我宣佈另一個接口就像這個 已IMethod財產。

public interface IFoo 
{ 
    IMethod MethodCaller { get ; set; } 
} 

現在我去了我的IFoo接口在我的類之一,我想從中調用IMethods方法。

類實現

public MyClass : IFoo 
{ 
    public IMethod MethodCaller{ get ; set; } 
} 

我該怎麼做呢?我如何調用添加更新從MyClass的

MyClasses實現IMethod刪除方法如下:

public class foo1:IMethod 
{ 

     public String Add(string str){ return string.Empty;} 

     Boolean Update(string str){//defination} 

     Boolean Delete(int id){ //defination} 
} 

public class foo2:IMethod 
{ 

     public String Add(string str){ return string.Empty;} 

     Boolean Update(string str){//defination} 

     Boolean Delete(int id){ //defination} 
} 
+1

?什麼是實現IMethod的類?你的MyClass只實現IFoo。 –

回答

1

內部類:

public MyClass : IFoo 
{ 
    public void CallAllMethodsOfIIMethodImpl() 
    { 
     if (this.MethodCaller != null) 
     { 
      this.MethodCaller.Add(...); 
      this.MethodCaller.Delete(...); 
      this.MethodCaller.Update(...); 
     } 
    } 
} 

外:

MyClass instance = new MyClass(); 
if (instance.MethodCaller != null) 
{ 
    instance.MethodCaller.Add(...); 
    instance.MethodCaller.Delete(...); 
    instance.MethodCaller.Update(...); 
} 
1

您還沒有定義實現IMethod任何具體的類 - 你只需要定義了屬性,該類型的類型爲IMethod - 現在您需要爲該屬性指定一個具體類,以便您可以調用其上的方法。一旦你這樣做,你可以簡單地調用您的MethodCaller屬性方法:

string result = MethodCaller.Add(someFoo); 
0

鑑於myClassMyClass實例和MethodCaller已被設置爲一個具體的實現,你可以這樣調用方法:

myClass.MethodCaller.Add(...); 
myClass.MethodCaller.Update(...); 
myClass.MethodCaller.Delete(...); 
0

你必須創建一個內部類implementsIMethod接口。

public MyClass : IFoo 
{ 
    private TestClass _inst; 
    public IMethod MethodCaller 
    { 
    get 
     { 
     if(_inst==null) 
      _inst=new TestClass(); 
     return _inst; 
     } 
     set 
     { 
      _inst=value; 
     } 
    } 
    public class TestClass : IMethod 
    { 
    public String Add(string str) {} 
    public Boolean Update(string str) {} 
    public Boolean Delete(int id) {} 
    } 
} 

調用方法:

MyClass instance=new MyClass(); 
instance.MethodCaller.Add(..); 

OR

IMethod call=new MyClass().MethodCaller; 
call.Add(..); 
相關問題