且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-20 02:16:10

在C ++/CLI中,简单"属性是getter&未声明setter.具有非平凡的属性,吸气剂显式声明了setter,其语法比C#的属性语法更像是普通的方法声明.

In C++/CLI, a 'trivial' property is one where the getter & setter is not declared. With a non-trivial property, the getter & setter are declared explicitly, with syntax that's more like a normal method declaration than C#'s property syntax.

public interface class IThisIsWhatANonIndexedNonTrivialPropertyLooksLike
{
    property String^ MyProperty { String^ get(); void set(String^ value); }
};

由于索引属性不允许使用琐碎的语法,因此我们需要对索引属性执行此操作.

Since the trivial syntax isn't allowed for indexed properties, we need to do that for your indexed property.

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";
}

输出:

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