2011-10-14 131 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(..); 
相关问题