C#运算符重载

闲来无事,突发奇想,C#提供的基本类型可以进行运算符操作,那么自己创建的类型应该也可以进行运算符操作吧?

既然有了想法就要尝试着去实现,打开《CSharp Language Specification》,寻找方案。

扩展一下

在这里说明一下《CSharp Language Specification》这个手册,真心不错。

C#语言规范(CSharp Language Specification doc) 
一个微软官方的说明文档。 
当你安装完Visual Studio的以后,默认安装目录下就会有这个东西,一般在 C:Program FilesMicrosoft Visual Studio 10.0VC#Specifications2052 下

知识点总结

  • 所有一元和二元运算符都具有可自动用于任何表达式的预定义实现。除了预定义实现外,还可通过在类或结构中包括 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     }