【发布时间】:2014-02-22 16:03:06
【问题描述】:
我认为 == 下面代码中的重载是不必要的,因为 == 如果未重载,则已经比较引用。请告知我的方式。应该用一个参数 Equals 和分别包含的 null 比较来完成?
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public override bool Equals(object param)
{
// If the cast is invalid, the result will be null
Student student = param as Student;
// Check if we have valid not null Student object
if (student == null)
{
return false;
}
// Compare the reference type member fields
if (!Object.Equals(this.Name, student.Name))
{
return false;
}
// Compare the value type member fields
if (this.Age != student.Age)
{
return false;
}
return true;
}
public static bool operator ==(Student student1, Student student2)
{
return Student.Equals(student1, student2);
}
public static bool operator !=(Student student1, Student student2)
{
return !(Student.Equals(student1, student2));
}
...
}
【问题讨论】:
-
添加语言标签。
-
这是 c#....? SO上有很多种语言
标签: c# operator-overloading equals