在这里的工作中,我们主要使用德尔福,但也有一些C#。
今天,一所大学问了我一个有趣的问题:如何在C#中执行内部映射?既然我不知道有个问题要问你:
首先是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#中执行接口映射
发布于 2017-10-31 06:29:55
为了从IMyFirstInterface接口访问方法,需要显式定义对象的类型:
IMyFirstInterface obj = new CombinedObject();
obj.DoSomethingInteresting(); //Method is accessible另一方面,如果实例化了CombinedObject类型的对象,那么上面的行将调用CombinedObject方法。
var obj = new CombinedObject();
obj.DoSomethingInteresting();隐式实现的接口方法将被调用:public void DoSomethingInteresting()
https://stackoverflow.com/questions/47028950
复制相似问题