如果一个类调用多个接口,且多个接口中有同名的函数,我们知道,如果类要继承一个接口,就必须要实现接口中的所有函数,怎么办?
C#的处理原则是:
在类中要分别实现每个接口及其函数,函数名前要加上接口的名称(前面的访问修饰符不用加,因为都是public).在调用此类中函数时,要把类别成对应的接口再调用接口对应的函数。
如下代码图:
1.两个接口
public interface inter1 { void setname(string sname); string getname(); } public interface inter2 { void setname(string sname); string getname(); }
2.创建类并实现以上两个接口
public class Myclass : Object, inter1, inter2 { private string name=""; void inter1.setname(string sname) { MessageBox.Show("Set inter1 name"); name = sname; } void inter2.setname(string sname) { MessageBox.Show("Set inter2 name"); name = sname; } string inter1.getname() { MessageBox.Show("Get inter1 name"); return name; } string inter2.getname() { MessageBox.Show("Get inter2 name"); return name; } }
3.调用以上类的相关函数
private void button1_Click(object sender, EventArgs e) { Myclass myclass=new Myclass(); inter1 i1 = (inter1)myclass;//强制类型转换 i1.setname("vvv"); inter2 i2 = (inter2)myclass;//强制类型转换 i2.getname(); }
Delphi的处理原则是:
给同名的函数分别设置别名,再分别实现以别名为名句的函数,以后类在调用时就是别名即可。
代码如下:
1.声明接口
type IInter1=interface ['{769D95CA-90CE-41BA-A195-A6F43A30A3FC}'] function getname:string; procedure setname(sname:string); end; IInter2=interface ['{1CE978B4-F7AC-44B1-9EAD-5B8CCE1510A1}'] function getname:string; procedure setname(sname:string); end;
2.创建类
声明部分
type TMyClass=class(TInterfacedobject,IInter1,IInter2) private FName:string; public { DONE : 设定别名 } function IInter1.getName=Inter1_getname; function IInter2.getName=Inter2_getname; procedure IInter1.setname=Inter1_setname; procedure IInter2.setname=Inter2_setname; { DONE : 重新命名 } function Inter1_getname:string; function Inter2_getname:string; procedure Inter1_setname(sname:string); procedure Inter2_setname(sname:string); { DONE : 析构 } destructor destroy;override; end;
实现部分
{ TMyClass } destructor TMyClass.destroy; begin MessageDlg('exit object',mtinformation,[mbok],0); inherited; end; function TMyClass.Inter1_getname: string; begin MessageDlg('get inter1 name',mtinformation,[mbok],0); Result:=FName; end; procedure TMyClass.Inter1_setname(sname: string); begin MessageDlg('set inter1 name',mtinformation,[mbok],0); FName:=sname; end; function TMyClass.Inter2_getname: string; begin MessageDlg('get inter2 name',mtinformation,[mbok],0); Result:=FName; end; procedure TMyClass.Inter2_setname(sname: string); begin MessageDlg('set inter2 name',mtinformation,[mbok],0); FName:=sname; end;
3.调用以上类中的函数:
procedure TForm1.Button1Click(Sender: TObject); begin myclass:=TMyClass.Create; try myclass.Inter1_setname('88'); ShowMessage(myclass.Inter2_getname); finally myclass.Free; end; end;