CLR via C#: 关于equals

//关于Equals /* 若目的是判断引用是否相等,最好不要用equals,而是用Reference-Equals. 这是因为equals可能被重写. 如下示例,如果你想判断个g1,g2是否是同一个引用,但是Stduent中却重写了Equals,故结果是 False.而ReferenceEquals(g1, g2)的结果正是你正真想要的. */ using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; public sealed class Program { class Student { public int Id; public Student(int id) { Id = id; } public override Boolean Equals(object o) { Console.WriteLine("in Student::Equals"); if (o is Student) { return Id == ((Student)o).Id; } else { throw new ArgumentException("the o is not student"); } } } class GoodStudent : Student { public GoodStudent(int id) : base(id) { } } public static void Main() { GoodStudent g1 = new GoodStudent(1); GoodStudent g2 = new GoodStudent(2); Console.WriteLine(g1.Equals(g2)); Console.WriteLine(ReferenceEquals(g1, g2)); } } //注意,基本数据类型,字符串的equals方法是比较值. //如下: public static void Main() { string s1 = "hi"; string s2 = "hi"; Console.WriteLine(s1.Equals(s2));//return Ture }

你可能感兴趣的:(CLR via C#: 关于equals)