Properties 如何在C++/CLI接口

Properties 如何在C++/CLI接口,properties,interface,c++-cli,default,indexer,Properties,Interface,C++ Cli,Default,Indexer,如何在C++/CLI接口中声明默认索引属性。 (请原谅重复,完全合格的符号,因为我正在学习C++或CLI,并且希望确保C++和C语言之间没有语言原语的混合) 代码是 public interface class ITestWithIndexer { property System::String ^ default[System::Int32]; } 编译器总是抛出“错误C3289:“默认值”一个普通属性不能被索引。” 我的错误在哪里 PS:在C#中,它只是 public interf

如何在C++/CLI接口中声明默认索引属性。
(请原谅重复,完全合格的符号,因为我正在学习C++或CLI,并且希望确保C++和C语言之间没有语言原语的混合) 代码是

public interface class ITestWithIndexer
{
    property System::String ^ default[System::Int32];
}
编译器总是抛出“错误C3289:“默认值”一个普通属性不能被索引。”
我的错误在哪里

PS:在C#中,它只是

public interface ITestWithIndexer
{
    System.String this[System.Int32] { get; set; }
}
如何将其转换为C++/CLI

谢谢

一个“平凡属性”是编译器可以自动生成getter和setter的属性,从属性声明中推断它们。这对于索引属性不起作用,编译器不知道应该如何处理索引变量。因此,必须显式声明getter和setter。与C#声明不同,减去语法sugar。Ecma-372第25.2.2章有一个例子。适合您的情况:

public interface class ITestWithIndexer {
    property String ^ default[int] { 
        String^ get(int);
        void set(int, String^);
    }
};

在C++/CLI中,“平凡”属性是未声明getter和setter的属性。通过一个非平凡的属性,getter和setter被显式声明,其语法更像是一个普通的方法声明,而不是C#的属性语法

public interface class IThisIsWhatANonIndexedNonTrivialPropertyLooksLike
{
    property String^ MyProperty { String^ get(); void set(String^ value); }
};
由于索引属性不允许使用普通语法,因此我们需要对索引属性执行此操作

public interface class ITestWithIndexer
{
    property String^ default[int]
    {
        String^ get(int index); 
        void set(int index, String^ value);
    }
};
以下是我的测试代码:

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";
}
public ref类TestWithIndexer:public ITestWithIndexer
{
公众:
属性字符串^default[int]
{
虚拟字符串^get(整数索引)
{
Debug::WriteLine(“TestWithIndexer::default::get({0})调用”,index);
返回索引.ToString();
}
虚拟无效集(整数索引,字符串^value)
{
Debug::WriteLine(“TestWithIndexer::default::set({0})={1}”,索引,值);
}
}
};
int main(数组^args)
{
ITestWithIndexer^test=gcnew TestWithIndexer();
Debug::WriteLine(“索引器返回了''+test[4]+''”);
测试[5]=“foo”;
}
输出:

TestWithIndexer::default::get(4) called The indexer returned '4' TestWithIndexer::default::set(5) = foo 调用TestWithIndexer::default::get(4) 索引器返回“4” TestWithIndexer::default::set(5)=foo
谢谢你的详细回答!解决了问题!:)谢谢你的补充信息!有时,我觉得C#编译器有点纵容了我,因为我忽略了明显的想法,比如索引变量处理问题。。。但也许这是对的