编译器错误 CS0021
错误消息
无法将带 [] 的索引应用于“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
}
}