C#索引器

csharp

浏览数:385

2019-1-8

片段 1片段 2


基本用法

//定义元素存储数组和容量
private string[] namelist = new string[size];
static public int size = 10;

public string this[int index]
{
    get
    {
        string tmp;

        if (index >= 0 && index <= size - 1)
        {
            tmp = namelist[index];
        }
        else
        {
            tmp = "";
        }

        return (tmp);
    }
    set
    {
        if (index >= 0 && index <= size - 1)
        {
            namelist[index] = value;
        }
    }
}

IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";


索引器重载

//索引器通过[名字&课程编号]查找和保存成绩
public int this[string stuName, int courseId]
{
    get
    {
    }
    set
    {
    }
}

//索引器重载,根据[名字]查找所有成绩
public List<Scores> this[string stuName]
{
    get
    {
        List<Scores> tempList = listScores.FindAll(x => x.StuName == stuName);
        return tempList;
    }
}

//多参数索引器和索引器重载          
FindScore fScore = new FindScore();
fScore["张三", 1] = 98;
fScore["张三", 2] = 100;
fScore["张三", 3] = 95;
fScore["李四", 1] = 96;

//查找所有张三的成绩
List<Scores> listScores = fScore["张三"];