簡體   English   中英

如何調用類中實現的接口的方法?

[英]how to call methods of a interface implemented in a class?

我有一個界面

 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調用Add Update Delete方法

實現IMethod的MyClasses如下:

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

您還沒有定義一個實現任何具體的類IMethod -你只定義了一個屬性,它的類型是IMethod -現在你需要一個具體的類分配給此屬性,以便您可以調用它的方法。 完成后,您只需調用MethodCaller屬性上的方法:

string result = MethodCaller.Add(someFoo);

在課堂內:

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

鑒於myClassMyClass一個實例,並且MethodCaller已設置為具體實現,您可以調用這樣的方法:

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

您必須創建一個implements IMethod接口的內部類。

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

要么

 IMethod call=new MyClass().MethodCaller;
 call.Add(..);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM