編譯器錯誤 CS0021
更新:2007 年 11 月
錯誤訊息
無法套用有 [] 的索引至型別 'type' 的運算式
嘗試透過不支援索引子 (C# 程式設計手冊) 的資料型別上的索引子來存取值。
當您嘗試在 C++ 組件內使用索引子時,可能會得到 CS0021。在此情況下,請以 DefaultMember 屬性裝飾 C++ 類別,以便讓 C# 編譯器知道哪個索引子為預設值。下列範例會產生 CS0021:
範例
這個檔案會編譯為 .dll 檔 (且 DefaultMember 屬性標記為註解),以產生錯誤。
// CPP0021.cpp
// compile with: /clr /LD
using namespace System::Reflection;
// Uncomment the following line to resolve
//[DefaultMember("myItem")]
public ref class MyClassMC
{
public:
property int myItem[int]
{
int get(int i){ return 5; }
void set(int i, int value) {}
}
};
下列為呼叫 .dll 檔的 C# 檔案。這個檔案會嘗試透過索引子存取類別,但由於沒有任何成員宣告為要使用的預設索引子,因此而產生錯誤。
// CS0021.cs
// compile with: /reference:CPP0021.dll
public class MyClass
{
public static void Main()
{
MyClassMC myMC = new MyClassMC();
int j = myMC[1]; // CS0021
}
}