开始复习到索引器这一块,刚开始发现好像也没啥用啊,然后上网搜了一下,我的天,我好肤浅。
先肤浅的讲一下索引器。
什么叫索引器呢?索引器就是一组get和set访问器,与属性相似,都不需要重新分配内存。
索引器的声明与属性有相似也有区别的,现在写一下索引器的声明。
public T this[int index]
{
set
{
}
get
{
}
}
这里的T不用我说了吧,泛型。声明与属性不同的就是,这里需要有个方括号,里面会定义一些数据,相当于参数,可以有多个,但是不能没有!下面写一个官方的索引器的使用吧。继续上代码:
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
set{arr[i] = value;}
get{return arr[i];}
}
}
class Program
{
//调用索引器
static void Main()
{
SampleCollection<string> sc = new SampleCollection<string>();
sc[0] = "Hello World!";
Console.WriteLine(sc[0]);
Console.ReadLine();
}
}
是不是很简单,肯定很多人跟我一样不知所措了,这怎么用?一脸懵逼。
那么下面上一个网友的用法。(PS:纯属抄袭,作者莫怪)
namespace Study
{
class Program
{
static void Main(string[] args)
{
ScoreIndex s = new ScoreIndex();
s["张三", 1] = 90;
s["张三", 2] = 100;
s["张三", 3] = 80;
s["李四", 1] = 60;
s["李四", 2] = 70;
s["李四", 3] = 50;
Console.WriteLine("张三课程编号为1的成绩为:" + s["张三",1]);
Console.WriteLine("张三的所有成绩为:");
ArrayList temp;
temp = s["张三"];
foreach (IndexClass b in temp)
{
Console.WriteLine("姓名:" + b.Name + "课程编号:" + b.CourseID + "分数:" + b.Score);
}
Console.ReadKey();
}
}
class IndexClass
{
private string _name;
private int _courseid;
private int _score;
public IndexClass(string _name, int _courseid, int _score)
{
this._name = _name;
this._courseid = _courseid;
this._score = _score;
}
public string Name
{
get { return _name; }
set { this._name = value; }
}
public int CourseID
{
get { return _courseid; }
set { this._courseid = value; }
}
public int Score
{
get { return _score; }
set { this._score = value; }
}
}
class ScoreIndex
{
private ArrayList arr;
public ScoreIndex()
{
arr = new ArrayList();
}
public int this[string _name, int _courseid]
{
get
{
foreach (IndexClass a in arr)
{
if (a.Name == _name && a.CourseID == _courseid)
{
return a.Score;
}
}
return -1;
}
set
{
arr.Add(new IndexClass(_name, _courseid, value)); //arr["张三",1]=90
}
}
//重载索引器
public ArrayList this[string _name]
{
get
{
ArrayList temp = new ArrayList();
foreach (IndexClass b in arr)
{
if (b.Name == _name)
{
temp.Add(b);
}
}
return temp;
}
}
}
}
所以还是很有用的,很牛逼的。好了,就讲到这里了,我再观摩观摩代码。