如何在 C++/CLI 接口中声明默认索引属性。
(请原谅使用命名空间的重复、完全限定符号,因为我刚刚学习 C++/CLI,并且希望确保 C++ 和 C# 之间不会发生语言原语的意外混淆)
Code is
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?
Thanks!!
在 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";
}
Output:
TestWithIndexer::default::get(4) called
The indexer returned '4'
TestWithIndexer::default::set(5) = foo
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)