在咱們編寫代碼的過程當中常常有這樣的需求,好比添加一條數據,咱們想要的結果是若是添加成功了就返回true,若是添加失敗了就返回false,在返回false的同時攜帶錯誤信息,咱們一般的作法是定義這樣的方法 ide
1 public bool Add(string name,out string error)
雖說這樣寫能夠符合咱們的需求,當是總以爲不對勁,並且很麻煩,在接收時還有定義一個接收error的變量,對於咱們這些coder來講就是用戶體驗很差,因而我冥思苦想,寫了個結構來提供這個用戶體驗,下面是結構代碼:測試
1 public struct Can 2 { 3 private bool _isTrue; 4 5 public string Error { get; set; } 6 7 public static bool operator true(Can param) 8 { 9 return param._isTrue == true; 10 } 11 12 public static bool operator false(Can param) 13 { 14 return param._isTrue == false; 15 } 16 17 public static bool operator !(Can param) 18 { 19 return !param._isTrue; 20 } 21 22 public static bool operator ==(Can arg1, bool arg2) 23 { 24 return arg1._isTrue == arg2; 25 } 26 27 public static bool operator !=(Can arg1, bool arg2) 28 { 29 return !(arg1._isTrue == arg2); 30 } 31 32 public static implicit operator Can(bool arg) 33 { 34 return new Can { _isTrue = arg }; 35 } 36 37 public static implicit operator bool(Can arg) 38 { 39 return arg._isTrue; 40 } 41 42 public static implicit operator Can(string arg) 43 { 44 return new Can { _isTrue = false, Error = arg }; 45 } 46 47 public override bool Equals(object obj) 48 { 49 if (!(obj is Can)) 50 return false; 51 52 Can can = (Can)obj; 53 54 return can._isTrue == this._isTrue && can.Error == this.Error; 55 } 56 57 public override int GetHashCode() 58 { 59 return this._isTrue.GetHashCode() ^ this.Error.GetHashCode(); 60 } 61 }
下面是用例代碼:this
1 public static Can Add(int number) 2 { 3 if (number < 0) 4 return "number 不能小於0"; 5 return true; 6 }
能夠同時返回String類型和Boolean類型,返回String是默認的Boolean爲false,主要是經過public static implicit operator Can(string arg)這個指針重寫的。spa
下面來看看測試結果:指針
1 public static void Main() 2 { 3 Can can = Add(1); 4 5 if (can == true) 6 Console.WriteLine("添加成功"); 7 8 if (!can) 9 Console.WriteLine(can.Error); 10 11 can = Add(-1); 12 13 if (can) 14 Console.WriteLine("添加成功"); 15 16 if (can == false) 17 Console.WriteLine(can.Error); 18 }
是否是很方便,嘻嘻。。。。code
若是你們有更好的方法,不妨拿出來分享下唄! xml