索引器语法一般用于容器类的API,没有特别的好处,就是形式上简洁一些。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp基础语法 { class MyArray { private int[] items; public MyArray(int capacity) { items = new int[capacity]; } public void SetItem(int i ,int val) { items[i] = val; } public int GetItem(int i) { return items[i]; } // 索引器 public int this[int index] { get { return items[index]; } set { items[index] = value; } } public int Size() { return this.items.Length; } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp基础语法 { class Program { static void Main(string[] args) { MyArray a = new MyArray(4); a[0] = 12; a[1] = 12; a[2] = 12; a[3] = 12; for(int i = 0; i < a.Size(); i++) { Console.WriteLine(a[i] + " "); } a.SetItem(0, 16); a.SetItem(0, 16); a.SetItem(0, 16); a.SetItem(0, 16); for (int i = 0; i < a.Size(); i++) { Console.WriteLine(a.GetItem(i) + " "); } Console.WriteLine("\n"); } } }MyFraction是一个类,也能支持乘法运算
在C#里面,可以重载操作符,
public static MyFraction operator *(MyFraction a, MyFraction b){ MyFraction result = new MyFraction(); result.num = a.num " b.num; result.den = a.den * b.den; return result; }