索引器 索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同的是索引器包含参数。 定义索引的方式和定义属性非常类似,主要有两部分:使用this关键词。定义一个索引值。 //本案例说明如何声明私有数组字段元元元myArray和索引器。通过使用索引器可直接访问实例 b[i] using System; class IndexerClass { private int [] myArray = new int[100]; public int this [int index] //索引声明 { get { if(index < 0 || index >= 100) return 0; else return myArray[index]; } set { if (!(index < 0 || index >= 100)) myArray[index] = value; } } } public class MainClass { public static void Main() { IndexerClass b = new IndexerClass(); b[3] = 256; b[5] = 1024; for (int i=0; i<=10; i++) { Console.WriteLine("Element #{0} = {1}", i, b[i]); } Console.ReadKey(); } } 结果分析: 索引器是为了实现对对象数组的索引访问。 运算符 运算符也是C#类的一个重要成员,系统对大部分运算符都给出了常规定义,这些定义大部分和现实生活中这些运算符的意义相同。但可以根据实际需要给这些运算符赋予一个新的含义,这就是运算符重载。运算符重载允许为运算指定用户定义的运算符实现,其中一个或两个操作数是用户定义的类或结构类型。C#中运算符重载的基本格式如下: 返回值类型 operator 运算符(运算对象列表){ 重载的实现部分;} //本案例定义了一个复数类,展示了如何使用运算符重载复数加法运算。 例如下面的复数类complex重载了常规的加法(+)和ToString方法,以实现复数类的操作功能。 using System; public struct Complex { public int real; public int imaginary; public Complex(int real, int imaginary) { this.real = real; this.imaginary = imaginary; } public static Complex operator +(Complex c1, Complex c2) { return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary); } public override string ToString() { return(String.Format("{0} + {1}i", real, imaginary)); } public static void Main() { Complex num1 = new Complex(2,3); Complex num2 = new Complex(3,4); Complex sum = num1 + num2; Console.WriteLine("First complex number: {0}",num1); Console.WriteLine("Second complex number: {0}",num2); Console.WriteLine("The sum of the two numbers: {0}",sum); Console.ReadKey(); } } (To be continued)

评论