我需要编写一个方法,该方法将两个员工对象作为输入参数,并比较它们的ID,以确定它们是否匹配。
目前尚不完整;但到目前为止,我有一个Employee类,该类从“ Person”类继承名字和姓氏属性,并以ID作为其自己的属性。我正在员工文件中编写该方法,并且已经在我的程序中实例化了2个示例员工。至于重载==的问题,我遇到一个错误,说“雇员”定义了运算符==,但没有覆盖Object.Equals。”它还说我需要定义“!=“,但我对此感到困惑当甚至没有考虑到此方法时,如何设置!=重载。
我看过两种比较方法,一种返回true或false,另一种简单地将“ match”写入控制台。这两种方法都可以满足我的目的,但是我无法找出错误的解决方法,也无法在这种情况下更改代码以确定2个员工ID之间的匹配。这是下面的代码;对于可能出了什么问题,我将不胜感激! (我感觉它可能会很不正常)。我也不确定如何调用该方法,但是我目前正在设法弄清楚。
程序文件:
namespace OperatorOverload
{
class Program
{
static void Main(string[] args)
{
Employee example = new Employee();
example.FirstName = "Kitty";
example.LastName = "Katz";
example.ID = 24923;
Employee example2 = new Employee();
example2.FirstName = "John";
example2.LastName = "Dudinsky";
example2.ID = 39292;
Console.ReadLine();
}
}
}
员工类别:
namespace OperatorOverload
{
class Employee : Person
{
public int ID { get; set; }
public static bool operator==(Employee employee, Employee employee2)
{
if (employee.ID == employee2.ID)
return true;
else
return false;
}
}
}
人员类别:
namespace OperatorOverload
{
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
答案 0 :(得分:2)
您还需要覆盖Equals
方法:
public override bool Equals(Object Obj)
{
Person person = obj as Person;
if(person == null)
return false;
return this.ID.Equals(person.ID);
}
Microsoft的recommandations:
在实现Equals时实施GetHashCode方法 方法。这样可以使Equals和GetHashCode保持同步。
在实现相等时覆盖Equals方法 运算符(==),并使它们执行相同的操作。
答案 1 :(得分:1)
您需要做的是使用Equals函数并像这样覆盖它:
public override bool Equals(object obj)
{
var item = obj as Employee;
if (item == null)
{
return false;
}
return this.ID.Equals(item.ID);
}
答案 2 :(得分:1)
编译器基本上是在告诉您,如果要重载Employee类的==运算符,则还必须重写Object.Equals方法和!=运算符,以便获得一致的语义,可以使用该语义比较Employee类型的实例。
这意味着您不必寻找变通方法:您只需要重载!=运算符并覆盖Object.Equals,以便按ID(而不是按引用)比较Employee对象(如果不这样做,则默认情况下会这样做)提供您自己的相等语义)。
答案 3 :(得分:1)
您应该使用此类。覆盖operator!=,
operator==
和Equals(object)
方法。
class Employee : Person
{
public int ID { get; set; }
public static bool operator ==(Employee employee, Employee employee2)
{
if (employee.ID == employee2.ID)
return true;
else
return false;
//but you should use
//return employee.ID == employee2.ID;
}
public static bool operator !=(Employee employee, Employee employee2)
{
return employee.ID != employee2.ID;
}
public override bool Equals(object obj)
{
var emp = obj as Employee;
if (emp == null)
return false;
return this.ID.Equals(emp.ID);
}
}
答案 4 :(得分:1)
这是重写Equals
方法的更好方法:
public override bool Equals(object obj)
{
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false; //optional. depends on logic
return this.ID.Equals(((Employee)obj).ID);
}