例如: public int this [int index] // indexer declaration { get { // Check the index limits if (index < 0 || index >= 100) return 0; else return myArray[index]; } set { if (!(index < 0 || index >= 100)) myArray[index] = value; } }
当我们访问类中一个集合时,希望类本身就像一个数组,因为除了这个集合外可能还有很多成员性质和方法。所以我们可以建立一个索引来访问,这样方便。 索引器是一种特殊的性质,包括get()和set()方法。其语法如何申明我就不再说了,大家都知道。关键是建立索引有何用处,先举个例子: public class ListIndexer { public ListIndexer(params string[] Strings) { //此处为处理字符串代码 } ..... ..... public int this[int index] { get { if (index < 0 || index >= 100) return 0; else return myArray[index]; } set { if (!(index < 0 || index >= 100)) myArray[index] = value; } } ..... ..... }
public int this [int index] // indexer declaration
{
get
{
// Check the index limits
if (index < 0 || index >= 100)
return 0;
else
return myArray[index];
}
set
{
if (!(index < 0 || index >= 100))
myArray[index] = value;
}
}
索引器是一种特殊的性质,包括get()和set()方法。其语法如何申明我就不再说了,大家都知道。关键是建立索引有何用处,先举个例子:
public class ListIndexer
{
public ListIndexer(params string[] Strings)
{
//此处为处理字符串代码
}
.....
.....
public int this[int index]
{
get
{
if (index < 0 || index >= 100)
return 0;
else
return myArray[index];
}
set
{
if (!(index < 0 || index >= 100))
myArray[index] = value;
}
}
.....
.....
}
可以用如下语法声明类中的索引器性质:类型 this[类型 参数]{get;set}例如:string mystring = arreylist [0];
可以把array象数组一样引用