[] 运算符被称为索引器。
索引器允许对对象进行索引,例如数组。当您为一个类定义一个索引器时,该类的行为类似于一个虚拟数组。然后,您可以使用数组访问运算符([ ])访问该类的实例。
索引器可以被重载。索引器也可以声明多个参数,并且每个参数可以是不同的类型。索引不一定必须是整数。
static 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; } } }
A B C D E F G H I J
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(); } } }
A B C C
以上是如何重载 C# 中的运算符?的详细内容。更多信息请关注PHP中文网其他相关文章!