C# 接口映射
在工作中,我们主要使用Delphi,但也使用了一些C。 所以今天一所大学问了我一个有趣的问题:我如何在C语言中执行Intreface映射?因为我不知道这里有个问题要问你: 首先是Delphi示例:C# 接口映射,c#,interface,C#,Interface,在工作中,我们主要使用Delphi,但也使用了一些C。 所以今天一所大学问了我一个有趣的问题:我如何在C语言中执行Intreface映射?因为我不知道这里有个问题要问你: 首先是Delphi示例: unit UnitInterfaceMapping; interface type IMyFirstInterface = interface(IInterface) procedure DoSomethingInteresting; procedure DoSomething
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中执行接口映射为了从IMyFirstInterface接口访问方法,您需要显式定义对象的类型:
IMyFirstInterface obj = new CombinedObject();
obj.DoSomethingInteresting(); //Method is accessible
另一方面,如果实例化CombinedObject类型的对象,则上面的行将调用void IMyFirstInterface.DoSomethingInteresting方法:
将调用隐式实现接口的方法:public void DoSomethingInterestingIMyFirstInterface obj=new CombinedObject;两种方法都可以。这里的问题是你有显式的接口实现。你应该看看隐式和显式的接口实现。这个问题可能对您有所帮助。谢谢您的回答:@JensBorrisholt欢迎您:
var obj = new CombinedObject();
obj.DoSomethingInteresting();