索引器允许对对象进行索引,例如数组。当您为一个类定义一个索引器时,该类的行为类似于一个虚拟数组。然后,您可以使用数组访问运算符([ ])访问该类的实例。
索引器可以被重载。索引器也可以声明多个参数,并且每个参数可以是不同的类型。索引不一定必须是整数。
示例1static void main(string[] args){ indexerclass team = new indexerclass(); team[0] = "a"; team[1] = "b"; team[2] = "c"; team[3] = "d"; team[4] = "e"; team[5] = "f"; team[6] = "g"; team[7] = "h"; team[8] = "i"; team[9] = "j"; for (int i = 0; i < 10; i++){ console.writeline(team[i]); } console.readline();}class indexerclass{ private string[] names = new string[10]; public string this[int i]{ get{ return names[i]; } set { names[i] = value; } }}
输出abcdefghij
example 2重写 []static class program{ static void main(string[] args){ indexerclass team = new indexerclass(); team[0] = "a"; team[1] = "b"; team[2] = "c"; for (int i = 0; i < 10; i++){ console.writeline(team[i]); } system.console.writeline(team["c"]); console.readline(); }}class indexerclass{ private string[] names = new string[10]; public string this[int i]{ get{ return names[i]; } set{ names[i] = value; } } public string this[string i]{ get{ return names.where(x => x == i).firstordefault(); } }}
输出abcc
以上就是如何重载 c# 中的运算符?的详细内容。
