2015-01-06 112 views
2

如何在C++/CLI接口中聲明默認索引屬性?
(請原諒與命名空間,因爲我剛開始學習C++/CLI,並希望確保C++和C#之間的語言基本沒有acciential的mixup發生重複,完全合格的符號)如何聲明C++/CLI接口中的默認索引屬性

代碼是

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嗎?

謝謝!

回答

5

在C++/CLI,一個瑣碎的屬性是一個設置吸氣劑&二傳手未聲明。使用一個非平凡的屬性,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) called 
The indexer returned '4' 
TestWithIndexer::default::set(5) = foo 
+0

感謝您的詳細解答!解決了這個問題! :) – Sascha

2

「不重要的屬性」是編譯器可以自動生成一個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^); 
    } 
}; 
+0

感謝您的附加信息!有時候,我覺得C#編譯器通過忽略索引變量處理問題等明顯的想法讓我感到有點受寵......但也許這是正確的。 :) – Sascha