繁体   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