运算符重载
下面的示例演示了一个化学反应,重载 +,表示对两种化学物品进行反应。
//化学分子式。H2-氢,O2-氧,H2O-水。 public enum MolecularFormulae {None, H2, O2, H2O }; public class Chemical { private MolecularFormulae _element; public MolecularFormulae Element { get { return _element; } set { _element = value; } } public Chemical(MolecularFormulae element) { Element = element; } //重载 public static Chemical operator +(Chemical c1, Chemical c2) { if (c1.Element == MolecularFormulae.H2 && c2.Element == MolecularFormulae.O2 || c1.Element == MolecularFormulae.O2 && c2.Element == MolecularFormulae.H2) { return new Chemical(MolecularFormulae.H2O); } return new Chemical(MolecularFormulae.None); } } public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Chemical c1 = new Chemical(MolecularFormulae.H2); Chemical c2 = new Chemical(MolecularFormulae.O2); Chemical c3 = c1 + c2; MessageBox.Show(c3.Element.ToString()); } }
索引器
我们见过 Param[i] 这一类的用法,这很可能就是索引器。
public class IntCollection { private int[] arr = new int[100]; public int this[int i] { get { return arr[i]; } set { arr[i] = value; } } } public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { IntCollection c = new IntCollection(); c[0] = 20; MessageBox.Show(c[0].ToString()); } }
我们可以看出索引器和属性非常相似,只不过 this[int i] 这里不同。
相关阅读