在 cli/c++ 中使用默认 属性 实现一个接口

Implement an interface with a default property, in cli/c++

我正在尝试将几个索引属性声明为 C# 中接口的一部分。 目的是能够写出类似的东西: int v=obj.Field1[4]+obj.Field2[4];

实现是在 C++/CLI 中完成的。

我找到了有关使用 'proxy' 处理行为的信息 Named indexed property in C#?

C#:

public interface IMyProp1
{
  int this[int idx] { get; }
}
public interface IMyProp2
{
  int this[int idx] { get; }
}


public interface IMyThing: IMyProp1, IMyProp2
{
 IMyProp1 Field1;
 IMyProp2 Field2;
}

在 C++/CLI 中,我在这里找到了一些信息: https://msdn.microsoft.com/en-us/library/2f1ec0b1.aspx 但它不具体关于接口 我写了以下内容(在 VS2015 编译器的帮助下反复试验)

public ref class MyThing: IMyThing
{
  virtual property int default[int]
  {
    int get(int idx) { return fld1[idx]; }
  }
  virtual property IMyProp1 Field1 { IMyProp1 get() { return this; } }
  virtual property IMyProp2 Field2 { IMyProp2 get() { return this; } }
private:
  array<int>^ fld1;
  array<int>^ fld2;

}

但我不知道如何实现 2 种不同的行为,因为

virtual property int default[int]

是独一无二的。即使有 2 个 'different' 接口(我承认它是相同的签名),我也想不出一种方法来指定 2 个不同的实现:

virtual property int IMyProp1::default[int] { int get(int idx) { return fld1[idx]; }
virtual property int IMyProp2::default[int] { int get(int idx) { return fld2[idx]; }

我找到了有关 C++ 中显式接口实现的信息

interface class MyInterface1 { void f(); };
interface class MyInterface2 { void f(); };
ref class MyClass : MyInterface1, MyInterface2
{
  public:
  virtual void f1() = MyInterface1::f
  {
    Console::WriteLine("MyClass::f1 == MyInterface1::f");
  }

  virtual void f2() = MyInterface2::f
  {
    Console::WriteLine("MyClass::f2 == MyInterface2::f");
  }
};

但无法找到将其与索引 属性 签名混合的方法。

对于属性的显式实现,您可以在每个访问器方法上指定显式覆盖。

试试这样的:

virtual property int Indexer1[int]
{
    int get(int idx) = IMyProp1::default[int]::get { return fld1[idx]; }
}