C#——运算符重载和索引器
一、什么是运算符?
所谓运算符重载,就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。自定义类的赋值运算符重载函数的作用与内置赋值运算符的作用类似,但是要要注意的是,它与拷贝构造函数与析构函数一样,要注意深拷贝浅拷贝的问题,在没有深拷贝浅拷贝的情况下,如果没有指定默认的赋值运算符重载函数,那么系统将会自动提供一个赋值运算符重载函数。
下面是个小例子:
namespace 运算符重载 { class Program { static void Main(string[] args) { Vector vect1 ,vect2,vect3; vect1 = new Vector(1.0, 4.0, 3.0); vect2 = new Vector(vect1); vect3 = vect1 + vect2; Console.WriteLine(vect3.ToString()); } } class Vector { private double x, y, z; public double X { get { return x; } set { x = value; } } public double Y { get { return y; } set { y = value; } } public double Z { get { return z; } set { z = value; } } public Vector () { x = 0; y = 0; z = 0; } public Vector (Vector rhs) { x = rhs.x; y = rhs.y; z = rhs.z; } public Vector (double x,double y,double z) { this.x = x; this.y = y; this.z = z; } public override string ToString() { return "X的坐标是:" + X +"Y的坐标是:" + Y+ "Z的坐标是:" + Z; } public static Vector operator +(Vector lhs,Vector rhs) { Vector result = new Vector(lhs); result.x += rhs.x; result.y += rhs.y; result.z += rhs.z; return result; } } }二、什么是索引器?
所谓的索引器,在语法上方便创建客户端应用程序可将其作为数组访问的类、结构或接口。类似与属性对类中成员变量起到了保护作用,体现了面向对象的一种属性——封装。经常是用是在主要用于封装内部集合或数组的类型中实现的。
下面是一个示例,希望通过这个例子能更好的了解什么是索引。
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Ablum MyAblum1 = new Ablum(2); Photo first = new Photo("小李"); Photo second = new Photo("小石"); MyAblum1[0] = first; MyAblum1[1] = second; Photo testPhots = MyAblum1[0]; Console .WriteLine(testPhots.Title ); Photo testPhotos = MyAblum1["小石"]; Console.WriteLine(testPhotos.Title); } } class Photo { private string PhotoTitle; public Photo() { PhotoTitle = "lee"; } public Photo (string title) { PhotoTitle = title; } public string Title { get { return PhotoTitle; } } } class Ablum { Photo[] photos; public Ablum () { photos = new Photo[3]; } public Ablum (int Capacity) { photos = new Photo[Capacity]; } public Photo this [int index] { get { if (index<0||index>=photos.Length ) { Console.WriteLine("索引有问题"); return null; } return photos[index]; } set { if (index < 0 || index >= photos.Length) { Console.WriteLine("索引有问题"); return; } photos[index]=value ; } } public Photo this [string title] { get { foreach (Photo p in photos ) { if (p.Title == title) return p; } Console.WriteLine("找不到"); return null; } } } }
最后更新:2017-04-03 12:54:02