[C#.NET 拾遺補漏]05:操作符的幾個騷操作
阿新 • • 發佈:2020-06-11
閱讀本文大概需要 1.5 分鐘。
大家好,這是極客精神【C#.NET 拾遺補漏】專輯的第 5 篇文章,今天要講的內容是操作符。 操作符的英文是 `Operator`,在數值計算中習慣性的被叫作運算子,所以在中文的概念中,運算子是操作符的一個子集。 操作符是很基礎的知識了,基礎歸基礎,我們來回顧一下 C# 操作符那些比較騷的操作,能想到的不多,請大家補充。 ## 操作符的過載 操作符過載大部分語言都沒有,而 C# 有。C# 允許使用者定義型別對操作符進行過載,方式是使用 `operate` 關鍵字把操作符寫成公開靜態函式。下面來演示一下過載 `+` 這個操作符。 我們建立一個 Complex 結構型別來代表一個複數,我們知道複數有實數和虛陣列成,於是可以這樣定義: ```cs public struct Complex { public double Real { get; set; } public double Imaginary { get; set; } } ``` 現在我們想實現複數的相加操作,即: ```cs Complex a = new Complex() { Real = 1, Imaginary = 2 }; Complex b = new Complex() { Real = 4, Imaginary = 8 }; Complex c = a + b; ``` 預設情況,自定義類是不能進行算術運算的,以上 `a + b` 會編譯報錯,我們需要對 `+` 進行操作符過載: ```cs public static Complex operator +(Complex c1, Complex c2) { return new Complex { Real = c1.Real + c2.Real, Imaginary = c1.Imaginary + c2.Imaginary }; } ``` C# 中像加減乘除等這類操作符都可以過載,也有些操作符是不能過載的,具體請檢視文末參考連結。 ## 隱式和顯式轉換操作符 我們知道子類可以隱式轉換為父類,在某種情況下(如父類由子類賦值而來)父類可以顯式轉換為子類。 在 C# 中,對於沒有子父類關係的使用者定義型別,也是可以實現顯式和隱式轉換的。C# 允許使用者定義型別通過使用 `implicit` 和 `explicit` 關鍵字來控制物件的賦值和物件的型別轉換。它的定義形式如下: ```cs public static