如何在C++/CLI界面中声明默认的索引属性

Sas*_*cha 2 default c++-cli indexer properties interface

如何在C++/CLI - Interface中声明默认的索引属性.
(请原谅重复的,完全限定的命名空间符号,因为我只是学习C++/CLI,并且希望确保C++和C#之间没有语言原语的混淆)

代码是

public interface class ITestWithIndexer
{
    property System::String ^ default[System::Int32];
}
Run Code Online (Sandbox Code Playgroud)

编译器总是抛出"错误C3289:'默认'一个普通的属性不能被索引".
我的错误在哪里?

PS:在C#中,它就是这样

public interface ITestWithIndexer
{
    System.String this[System.Int32] { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如何将其转换为C++/CLI?

谢谢!!

Dav*_*Yaw 5

在C++/CLI中,'trivial'属性是未声明getter和setter的属性.使用非平凡属性,getter和setter是显式声明的,其语法更像是普通的方法声明,而不是C#的属性语法.

public interface class IThisIsWhatANonIndexedNonTrivialPropertyLooksLike
{
    property String^ MyProperty { String^ get(); void set(String^ value); }
};
Run Code Online (Sandbox Code Playgroud)

由于索引属性不允许使用普通语法,因此我们需要为索引属性执行此操作.

public interface class ITestWithIndexer
{
    property String^ default[int]
    {
        String^ get(int index); 
        void set(int index, String^ value);
    }
};
Run Code Online (Sandbox Code Playgroud)

这是我的测试代码:

public ref class TestWithIndexer : public ITestWithIndexer
{
public:
    property String^ default[int] 
    {
        virtual String^ get(int index)
        {
            Debug::WriteLine("TestWithIndexer::default::get({0}) called", index);
            return index.ToString();
        }
        virtual void set(int index, String^ value)
        {
            Debug::WriteLine("TestWithIndexer::default::set({0}) = {1}", index, value);
        }
    }
};

int main(array<System::String ^> ^args)
{
    ITestWithIndexer^ test = gcnew TestWithIndexer();
    Debug::WriteLine("The indexer returned '" + test[4] + "'");
    test[5] = "foo";
}
Run Code Online (Sandbox Code Playgroud)

输出:

TestWithIndexer::default::get(4) called
The indexer returned '4'
TestWithIndexer::default::set(5) = foo