C#運(yùn)算符重載實(shí)例淺析
作者:佚名 
  C#運(yùn)算符重載實(shí)例向你介紹了在實(shí)際操作中C#運(yùn)算符重載的實(shí)例應(yīng)用情況。
 C#運(yùn)算符重載實(shí)例是掌握C#運(yùn)算符重載的有效方法,那么就讓我們通過(guò)一個(gè)實(shí)際的例子來(lái)介紹。其中重載==,!=,Equal,GetHashCode函數(shù)。
- public class Record
 - {
 - public string[] arr = null;
 - public bool hasEqual = false;
 - //重載一個(gè)下標(biāo)運(yùn)算符號(hào)
 - public string this[int index]
 - {
 - get
 - {
 - return arr[index];
 - }
 - set
 - {
 - arr[index] = value;
 - }
 - }
 - public override int GetHashCode()
 - {
 - //在這里使用字符串?dāng)?shù)組的hashcode,避免自己完成一個(gè)算法
 - return arr.GetHashCode();
 - }
 - public Record(int count)
 - {
 - if (count < 1)
 - {
 - throw new Exception("數(shù)組的長(zhǎng)度不能小于1");
 - }
 - arr = new string[count];
 - }
 - public static bool operator ==(Record rec1, Record rec2)
 - {
 - //注意我們調(diào)用Equals來(lái)判斷是否相等。而不是在自己的函數(shù)中判斷。
 - //這是因?yàn)槿绻谧约旱暮瘮?shù)中判斷。
 - //比如有rec2=null的情況。如果是這種情況。我們要判斷if(rec2==null){…}。
 - //其中rec2==null也是調(diào)用一個(gè)等號(hào)運(yùn)算符,這里面有一個(gè)遞歸的過(guò)程,造成了死循環(huán)。
 - return Object.Equals(rec1, rec2);
 - }
 - public static bool operator !=(Record rec1, Record rec2)
 - {
 - return !Object.Equals(rec1, rec2);
 - }
 - public override bool Equals(object obj)
 - {
 - //判斷與之比較的類型是否為null。這樣不會(huì)造成遞歸的情況
 - if (obj == null)
 - return false;
 - if (GetType() != obj.GetType())
 - return false;
 - Record rec = (Record)obj;
 - int count = rec.arr.Length;
 - for (int i = 0; i < count; i++)
 - {
 - if (this.arr[i] != rec.arr[i])
 - {
 - return false;
 - }
 - }
 - return true;
 - }
 - }
 
C#運(yùn)算符重載實(shí)例的基本情況就向你介紹到這里,希望對(duì)你有所幫助。
【編輯推薦】
責(zé)任編輯:仲衡 
                    來(lái)源:
                    中國(guó)自學(xué)編程網(wǎng)
 














 
 
 
 
 
 
 