【问题标题】:How to declare the default indexed property in C++/CLI interface如何在 C++/CLI 接口中声明默认索引属性
【发布时间】:2015-03-04 10:37:25
【问题描述】:

如何在 C++/CLI - 接口中声明默认索引属性。
(请原谅重复的、完全限定的命名空间符号,因为我只是在学习 C++/CLI,并希望确保不会发生 C++ 和 C# 之间的语言原语意外混淆)

代码是

public interface class ITestWithIndexer
{
    property System::String ^ default[System::Int32];
}

编译器总是抛出“error C3289: 'default' a trivial property cannot be indexed”。
我的错误在哪里?

PS:在 C# 中,它只是

public interface ITestWithIndexer
{
    System.String this[System.Int32] { get; set; }
}

如何将其翻译成 C++/CLI?

谢谢!!

【问题讨论】:

    标签: properties interface c++-cli default indexer


    【解决方案1】:

    “普通属性”是编译器可以自动生成 getter 和 setter,从属性声明中推导出来的属性。这不适用于索引属性,编译器不知道它应该如何处理索引变量。因此,您必须明确声明 getter 和 setter。与 C# 声明没有什么不同,只是减去了语法糖。 Ecma-372,第 25.2.2 章有一个例子。适应您的情况:

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

    【讨论】:

    • 感谢您提供更多信息!有时,通过忽略索引变量处理问题等明显的想法,我觉得 C# 编译器有点纵容……但也许那是对的。 :)
    【解决方案2】:

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

    输出:

    TestWithIndexer::default::get(4) 调用
    索引器返回“4”
    TestWithIndexer::default::set(5) = foo
    

    【讨论】:

    • 感谢您的详细解答!解决了问题! :)
    猜你喜欢
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 1970-01-01
    • 2020-03-02
    • 2020-04-29
    • 2020-01-30
    • 1970-01-01
    相关资源
    最近更新 更多