标签:on() sum VID names 操作符 ons png idt child
1.操作符概览
下面图中的优先级是从上往下递减,同行是从左往右递减。
操作符的本质就是函数(算法);比如说没有操作符+,那么我们做加法的时候只能先写一个Add方法,然后调用。
操作符不能脱离与它相关联的数据类型;
比如下面的代码:
int a=1; int b=2; int c=a/b;
c的结果一定是整数,因为这里的除号是int类型的除号。
但是如果是下面这种,那么就是精度高的除号,也就是double的除号:
double a = 1; int b = 2; double c = a / b;
(1)自定义一个操作符
下面代码实现了2个人结婚,并且婚后有很多孩子。
namespace TestClass { // class Program { static void Main(string[] args) { Person person1 = new Person(); Person person2 = new Person(); person1.Name = "Deer"; person2.Name = "Deer‘s wife"; List<Person> people = Person.GetMarry(person1,person2); foreach(var item in people) { Console.WriteLine(item.Name); } Console.ReadKey(); } } class Person { public string Name { get; set; } /// <summary> /// 结婚之后生孩子 /// </summary> /// <param name="person1"></param> /// <param name="person2"></param> /// <returns></returns> public static List<Person> GetMarry(Person person1, Person person2) { List<Person> people = new List<Person>(); people.Add(person1); people.Add(person2); for (int i = 0; i < 11; i++) { Person child = new Person() { Name = person1.Name + "&" + person2.Name + "s child" }; people.Add(child); } return people; } } }
就像之前说的,操作符的本质是算法的简记法。所以可以重写自定义的+号来表示。
namespace TestClass { // class Program { static void Main(string[] args) { Person person1 = new Person(); Person person2 = new Person(); person1.Name = "Deer"; person2.Name = "Deer‘s wife"; List<Person> people = person1 + person2; foreach(var item in people) { Console.WriteLine(item.Name); } Console.ReadKey(); } } class Person { public string Name { get; set; } /// <summary> /// 结婚之后生孩子 /// </summary> /// <param name="person1"></param> /// <param name="person2"></param> /// <returns></returns> public static List<Person> operator + (Person person1, Person person2) { List<Person> people = new List<Person>(); people.Add(person1); people.Add(person2); for (int i = 0; i < 11; i++) { Person child = new Person() { Name = person1.Name + "&" + person2.Name + "s child" }; people.Add(child); } return people; } } }
结果:
Deer Deer‘s wife Deer&Deer‘s wifes child Deer&Deer‘s wifes child Deer&Deer‘s wifes child Deer&Deer‘s wifes child Deer&Deer‘s wifes child Deer&Deer‘s wifes child Deer&Deer‘s wifes child Deer&Deer‘s wifes child Deer&Deer‘s wifes child Deer&Deer‘s wifes child Deer&Deer‘s wifes child
(2)操作符的优先级
引自于:https://www.bilibili.com/video/BV13b411b7Ht?p=10
标签:on() sum VID names 操作符 ons png idt child
原文地址:https://www.cnblogs.com/anjingdian/p/13193934.html