閑來無事,突發奇想,C#提供的基本類型可以進行運算符操作,那么自己創建的類型應該也可以進行運算符操作吧?
既然有了想法就要嘗試着去實現,打開《CSharp Language Specification》,尋找方案。
擴展一下
在這里說明一下《CSharp Language Specification》這個手冊,真心不錯。
C#語言規范(CSharp Language Specification doc)
一個微軟官方的說明文檔。
當你安裝完Visual Studio的以后,默認安裝目錄下就會有這個東西,一般在 C:\Program Files\Microsoft Visual Studio 10.0\VC#\Specifications\2052 下
知識點總結
- 所有一元和二元運算符都具有可自動用於任何表達式的預定義實現。除了預定義實現外,還可通過在類或結構中包括 operator 聲明來引入用戶定義的實現。
-
可重載的一元運算符 (overloadable unary operator) 有:
+ - ! ~ ++ -- true false
-
可重載的二元運算符 (overloadable binary operator) 有:
+ - * / % & | ^ << >> == != > < >= <=
小案例
有了相應的知識就練練手做一個案例吧,這里我做了一個 學生+學生 return 新的學生 的案例,xixi。
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //實例化一個男孩 6 Student boy = new Student() { Sex = true }; 7 //實例化一個女孩 8 Student girl = new Student() { Sex = false }; 9 Student student = boy + girl; 10 Console.WriteLine($"哇! 是個{(student.Sex?"男":"女")}孩"); 11 Console.ReadKey(); 12 } 13 14 } 15 class Student { 16 public bool Sex { get; set; } 17 public static Student operator +(Student stu1, Student stu2) 18 { 19 //當Sex不同的時候相加才能放回一個Student 20 if (stu1.Sex != stu2.Sex) 21 { 22 Random random = new Random(); 23 //返回一個隨機性別的Student 24 return new Student() { Sex = (random.Next(2) == 0) }; 25 } 26 return null; 27 } 28 public static Student operator !(Student student) 29 { 30 //轉變Sex 31 return new Student() { Sex=!student.Sex }; 32 } 33 }