我正在尝试覆盖C#中的Equals方法,我得到的错误就像
SoftCherry.Customer'是'类型',但用作'变量'
错误行:返回this.FirstName ==((客户).obj).FirstName&& this.LastName ==((Customer).obj).LastName; 在客户类
这是我的代码
using System;
namespace SoftCherry
{
public class MainClass
{
public static void Main()
{
Customer C1 = new Customer ();
C1.FirstName = "Raja";
C1.LastName = "Thananki";
Customer C2= new Customer ();
C2.FirstName = "Raja";
C2.LastName = "Thananki";
Console.WriteLine(C1== C2);
Console.WriteLine(C1.Equals(C2));
Console.ReadLine();
}
}
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (!(obj is Customer))
{
return false;
}
return this.FirstName == ((Customer).obj).FirstName &&
this.LastName == ((Customer).obj).LastName;
}
public override int GetHashCode()
{
return this.FirstName.GetHashCode() ^ this.LastName.GetHashCode();
}
}
}
答案 0 :(得分:3)
删除类型后的点:
return this.FirstName == ((Customer)obj).FirstName &&
this.LastName == ((Customer)obj).LastName;
否则它是无效的语法。
答案 1 :(得分:0)
您的代码应该使用(Customer)obj
,而不是(Customer).obj
。在你执行此演员表的任何地方都有一个错误的点。