首页 > 解决方案 > 将多个索引属性从 C# 导出到 tlb --> delphi

问题描述

我目前正在尝试重新实现一个 com 接口。这个接口目前在一个Delphi项目中使用。Delphi 接口代码可能是使用“TLIBIP.EXE -P”机器生成的)在这个自动生成的代码中,例如有这个接口:

IDPets = interface(IDispatch)
    ['{679DDC30-232F-11D3-B461-00A024BEC59F}']
    function Get_Value(Index: Integer): Double; safecall;
    procedure Set_Value(Index: Integer; Value: Double); safecall;
    function Get_Pet(Index: Integer): IDPets; safecall;
    procedure Set_Pet(Index: Integer; const Ptn: IDPets); safecall; 
    property Value[Index: Integer]: Double read Get_Value write Set_Value;
    property Pet[Index: Integer]: IDPets read Get_Pet write Set_Pet;
end;

如您所见,有多个属性可以像使用方括号的字段或数组一样访问。

到目前为止我取得了什么成就:

在 C# 中,可以使用此代码编写一个索引器访问器

[System.Runtime.CompilerServices.IndexerName("Cat")]
public ICat this[int index] { get; set; }

(来自:如何导出C#编写的接口实现TLB生成的Delphi代码

问题:

但是现在我需要在一个类中拥有多个索引器。它们只在返回类型上有所不同,所以我不能简单地重载“this”关键字。

那么有没有人知道如何在 C# 中实现它,以便获得一个 TLB 文件,该文件可用于生成您可以在本文顶部看到的 Delphi 代码?

任何想法都受到高度赞赏。

编辑:我已经偶然发现这篇文章https://stackoverflow.com/a/4730299/3861861 它有点工作,所以我可以将多个属性导出到 Delphi 的索引。但是这个属性的类型不是正确的。例如:双精度不是双精度,而是 IIndexerDouble(我需要从索引器中删除泛型以进行 com 导出,因此我必须为要使用的每种数据类型编写一个索引器)

标签: c#delphicomtlb

解决方案


您不需要“一个类中有多个索引器”。你真正需要的是在 Delphi 中有几个索引属性。

假设您要添加Dog索引属性。首先将这些常规方法添加到 C# 类:

public Dog GetDog(int index)
{
    ...
}

public void SetDog(int index, Dog value)
{
    ...
}

他们会生成这个:

function GetDog(Index: Integer): IDDogs; safecall;
procedure SetDog(Index: Integer; const Ptn: IDDogs); safecall; 

现在只需添加索引属性的声明:

property Dog[Index: Integer]: IDDogs read GetDog write SetDog;

推荐阅读