运算符重载

76 阅读1分钟
  1. 用==号判断两个对象的引用是否相等,实际上是比较地址,如果是同一个对象的引用,那地址就是一样的,结果就是true,否则,就是false
  2. 因为想要让==号比较两个对象是否相等(数据成员是否一样),所以就要用运算符重载,让==号直接比较两个对象数据成员

student类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _15_运算符重载
{
    internal class Student
    {
        private int age;
        private string name;
        private int id;

        public Student(int age, string name, int id)
        {
            this.age = age;
            this.name = name;
            this.id = id;
        }
        public static bool operator==(Student s1, Student s2)
        {
            if(s1.age == s2.age && s1.name == s2.name && s1.id == s2.id)
            {
                return true;
            } 
            return false;
        }
        public static bool operator !=(Student s1, Student s2)
        {
            bool result = s1 == s2;//相等则为true,否则为false
            return !result;
        }
    }
}

测试

internal class Program
{
    static void Main(string[] args)
    {
        Student s1 = new Student(20, "张三", 2123);
        Student s2 = new Student(20, "张三", 2123);

        Student s3 = s1;
        //Console.WriteLine(s1 == s3);
        Console.WriteLine(s1 == s2);
        Console.WriteLine(s2 != s2);
    }
}

总结

这里s1 == s2就用到了运算符重载,判断两个对象是不是一样,比较两个对象的数据成员,而不是比较引用(地址)