• .net -笔记 简单的操作符重载


    这个操作符重载很有意思
     1 class Program
     2 {
     3 static void Main(string[] args)
     4 {
     5 Person person1 = new Person() { Name = "LiLei", Age = 12 };
     6 Person person2 = new Person("HanMeimei", 11);
     7 Person person3 = person1 + person2;
     8 Person person4 = person1 == person2;
     9 Person person5 = 10;
    10 Console.WriteLine($"Name's merge is {person3.Name}
    Age's sum is {person3.Age}");
    11 Console.ReadKey();
    12 }
    13 }
    14 
    15 public class Person
    16 {
    17 public Person() { }
    18 public Person(string name, int age)
    19 {
    20 this.Name = name; this.Age = age;
    21 }
    22 public string Name { get; set; }
    23 public int Age { get; set; }
    24 public static Person operator +(Person p1, Person p2)
    25 {
    26 Person p3 = new Person(p1.Name + p2.Name, p1.Age + p2.Age);
    27 return p3;
    28 }
    29 
    30 public static Person operator ==(Person p1, Person p2)
    31 {
    32 Person p3 = new Person(p1.Name + p2.Name, p1.Age + p2.Age);
    33 return p3;
    34 }
    35 public static Person operator !=(Person p1, Person p2)
    36 {
    37 Person p3 = new Person(p1.Name + p2.Name, p1.Age + p2.Age);
    38 return p3;
    39 }
    40 
    41 public static implicit operator Person(int age)
    42 {
    43 return new Person();
    44 }
    45 }
    View Code
  • 相关阅读:
    一周内签到连续天数求解
    int型动态数组总结
    快速排序总结
    希尔排序总结
    冒泡排序的总结
    桶排序总结
    插入排序的总结
    选择排序的总结
    二分法的五种实现
    安装Yum源
  • 原文地址:https://www.cnblogs.com/Darren-xia/p/11825848.html
Copyright © 2020-2023  润新知