C#高级语法基础知识总结4——运算符
比较引用类型的相等性
- ReferenceEquals() 静态方法,不能重写,如果提供的两个引用引用同一个对象实例,则返回true,否则就返回false。Null=null
- 虚拟的Equals(),可在自己的类中重写
- 静态的Equals()方法
- 比较运算符(==)
比较值类型的相等性
采用与引用类型相同的规则:ReferenceEquals()用于比较引用,Equals()用于比较值,比较运算符可以看做一个中间项。但最大的区别是值类型需要装箱,才能把它们转换为引用,进而才能对它们执行方法。
运算符重载
运算符重载
1 2 3 Vector vector1, vector2, vector3; 4 5 vector1 = new Vector(3.0, 3.0, 1.0); 6 7 vector2 = new Vector(2.0, -4.0, -4.0); 8 9 vector3 = vector1 + vector2; 10 11 12 13 Console.WriteLine("vector1={0}" , vector1.ToString()); 14 15 Console.WriteLine("vector2={0}", vector2.ToString()); 16 17 Console.WriteLine("vector3={0}", vector3.ToString()); 18 19 20 21 vector1 = 2 * vector1; 22 23 Console.WriteLine("2*vector1={0}", vector1.ToString()); 24 25 26 27 28 29 struct Vector 30 31 { 32 33 private double _x, _y, _z; 34 35 public double X { get { return _x; } set { _x = value; } } 36 37 public double Y { get { return _y; } set { _y = value; } } 38 39 public double Z { get { return _z; } set { _z = value; } } 40 41 42 43 public Vector(double x, double y, double z) 44 45 { 46 47 this._x = x; 48 49 this._y = y; 50 51 this._z = z; 52 53 } 54 55 56 57 public Vector(Vector rhs) 58 59 { 60 61 _x = rhs._x; 62 63 _y = rhs._y; 64 65 _z = rhs._z; 66 67 } 68 69 70 71 public override string ToString() 72 73 { 74 75 return "(" + _x + "," + _y + "," + _z + ")"; 76 77 } 78 79 80 81 public static Vector operator +(Vector lhs, Vector rhs) 82 83 { 84 85 Vector result = new Vector(lhs); 86 87 result._x += rhs._x; 88 89 result._y += rhs._y; 90 91 result._z += rhs._z; 92 93 return result; 94 95 } 96 97 98 99 //数和向量相乘 100 101 public static Vector operator *(double lhs, Vector rhs) 102 103 { 104 105 return new Vector(lhs * rhs._x, lhs * rhs._y, lhs * rhs._z); 106 107 } 108 109 110 public static Vector operator *(Vector lhs, double rhs) 111 112 { 113 114 return rhs * lhs; 115 116 } 117 118 }
本是菜鸟,偶做老鸟,略读半卷书,坐井说天阔。大志无所为,海斗量得失,年到老时方恨晚,怒指生不逢时。