C# 索引器(智能阵列)
我们的班主任给了我们一个关于C# 索引器(智能阵列),c#,console-application,indexer,C#,Console Application,Indexer,我们的班主任给了我们一个关于索引器()的程序,当我在我的计算机上编译并执行该程序时,我得到的错误是 错误:1运算符“失败,因为编译器找不到名为Count的属性。相反,它找到了一个方法,或者这里没有显示,或者如果Program实现了,那么它很可能是Linq的扩展方法 尝试将计数属性添加到程序 class Program { ... public int Count { get { return this.array.Count; } } } 这将
索引器()
的程序,当我在我的计算机上编译并执行该程序时,我得到的错误是
错误:1运算符“失败,因为编译器找不到名为
Count
的属性。相反,它找到了一个方法,或者这里没有显示,或者如果Program
实现了,那么它很可能是Linq的扩展方法
尝试将计数
属性添加到程序
class Program
{
...
public int Count
{
get { return this.array.Count; }
}
}
这将解决编译器错误。现在,如果你想知道为什么要用…我想是因为你的老师想说明如何使用它们。索引器只是其中的一部分,它使编写类似
p.GetItem(i)
这样的代码看起来更干净,p[i]
我在您的程序中没有看到计数实现。添加Count实现并尝试重新编译
class Program
{
ArrayList array = new ArrayList();
public int Count { get { return array.Count; } }
public object this[int index]
{
get
{
if (index < 0 || index >= array.Count)
{
return (null);
}
else
{
return (array[index]);
}
}
set
{
array[index] = value;
}
}
}
类程序
{
ArrayList数组=新的ArrayList();
公共整数计数{get{return array.Count;}}
公共对象此[int索引]
{
收到
{
if(索引<0 | |索引>=array.Count)
{
返回(空);
}
其他的
{
返回(数组[索引]);
}
}
设置
{
数组[索引]=值;
}
}
}
您应该添加一个Count属性和一个将ArrayList初始化为正确大小的构造函数,如下所示:
class Program
{
ArrayList array = null;
public Program(int size)
{
array = new ArrayList(size);
}
public object this[int index]
{
get
{
if (index < 0 || index >= array.Count)
{
return (null);
}
else
{
return (array[index]);
}
}
set
{
array[index] = value;
}
}
public int Count
{
get
{
return array.Count;
}
}
}
类程序
{
ArrayList数组=null;
公共程序(整数大小)
{
数组=新的ArrayList(大小);
}
公共对象此[int索引]
{
收到
{
if(索引<0 | |索引>=array.Count)
{
返回(空);
}
其他的
{
返回(数组[索引]);
}
}
设置
{
数组[索引]=值;
}
}
公共整数计数
{
收到
{
返回数组.Count;
}
}
}
你希望p.Count
从哪里来?@Jon:奇怪的是,错误消息调用了p.Count
方法组<代码>类程序没有方法计数
。什么是p.计数?一种方法?如果是这样的话,i
可能会有帮助。@Vlad:是的,我觉得这也很奇怪。但这是OP至少应该看到的。你现在不应该再使用ArrayList
。你为什么把zour Y都当作Z的呢?@p.s.w.g哈哈。抱歉,更改了键盘布局,但没有注意到:-)
class Program
{
ArrayList array = null;
public Program(int size)
{
array = new ArrayList(size);
}
public object this[int index]
{
get
{
if (index < 0 || index >= array.Count)
{
return (null);
}
else
{
return (array[index]);
}
}
set
{
array[index] = value;
}
}
public int Count
{
get
{
return array.Count;
}
}
}