在工作中我们主要使用Delphi,还有一些C# 所以今天一所大学今天问我一个有趣的问题:如何在C#中执行Intreface映射?因为我不知道这是你的问题:
首先是Delphi示例:
unit UnitInterfaceMapping;
interface
type
IMyFirstInterface = interface(IInterface)
procedure DoSomethingInteresting;
procedure DoSomethingElse;
end;
IMyNextInterface = interface(IInterface)
procedure DoSomethingInteresting;
end;
TMyCombinedObject = class(TInterfacedObject, IMyFirstInterface, IMyNextInterface)
private
procedure IMyFirstInterface.DoSomethingInteresting = DoSomethingInterestingFirst;
procedure IMyNextInterface.DoSomethingInteresting = DoSomethingInterestingNext;
public
procedure DoSomethingInterestingFirst;
procedure DoSomethingInterestingNext;
procedure DoSomethingElse;
end;
implementation
uses
VCL.Dialogs;
{ TMyCombinedObject }
procedure TMyCombinedObject.DoSomethingElse;
begin
ShowMessage('DoSomethingElse');
end;
procedure TMyCombinedObject.DoSomethingInterestingFirst;
begin
ShowMessage('DoSomethingInterestingFirst');
end;
procedure TMyCombinedObject.DoSomethingInterestingNext;
begin
ShowMessage('DoSomethingInterestingNext');
end;
end.
表格我称之为代码:
uses
UnitInterfaceMapping;
procedure TForm14.Button1Click(Sender: TObject);
var
MyFirstInterface: IMyFirstInterface;
MyNextInterface: IMyNextInterface;
begin
MyFirstInterface := TMyCombinedObject.Create;
MyFirstInterface.DoSomethingInteresting;
MyFirstInterface.DoSomethingElse;
MyNextInterface := TMyCombinedObject.Create;
MyNextInterface.DoSomethingInteresting;
end;
结果是三个对话框,每个方法一个。
然后我尝试将其移植到C#:
using System;
namespace InterfaceMapping
{
public interface IMyFirstInterface
{
void DoSomethingInteresting();
void DoSomethingElse();
}
public interface IMyNextInterface
{
void DoSomethingInteresting();
}
public class CombinedObject : IMyFirstInterface, IMyNextInterface
{
public void DoSomethingInteresting()
{
throw new NotImplementedException();
}
void IMyFirstInterface.DoSomethingElse()
{
throw new NotImplementedException();
}
void IMyFirstInterface.DoSomethingInteresting()
{
throw new NotImplementedException();
}
}
class Program
{
static void Main(string[] args)
{
new CombinedObject() <== Problem
}
}
}
重点是在创建CombinedObject
的新实例时,我只看到DoSomethingInteresting
方法。
简而言之:如何在C#中执行接口映射
答案 0 :(得分:1)
为了从IMyFirstInterface
接口访问方法,您需要明确定义对象的类型:
IMyFirstInterface obj = new CombinedObject();
obj.DoSomethingInteresting(); //Method is accessible
另一方面,如果您实例化void IMyFirstInterface.DoSomethingInteresting()
类型的对象,则上面的行将调用CombinedObject
方法:
var obj = new CombinedObject();
obj.DoSomethingInteresting();
将调用隐式实现的接口方法:public void DoSomethingInteresting()