我创建了自定义链接列表类。在这堂课我有
public bool Contains( Object obj )
{
for( Node curr = Start; curr != null; curr = curr.Next)
{
if( curr.Data == obj )
return true;
}
return false;
}
在Workman.cs中我有覆盖==运算符:
class Workman
{
public DateTime Date { get; set; }
public string LastName { get; set; }
public string PartCode { get; set; }
public int PartCount { get; set; }
public int DaysWorked { get; set; }
public int PartsMade { get; set; }
public double PriceSum { get; set; }
public Workman(DateTime date, string lastName, string partCode, int partCount)
{
Date = date;
LastName = lastName;
PartCode = partCode;
PartCount = partCount;
}
public Workman() { }
public override string ToString ()
{
return string.Format ("[Workman: LastName={0}, PartCode={1}, PartCount={2}", LastName, PartCode, PartCount);
}
public override bool Equals (object obj)
{
return this.Equals (obj as Workman);
}
public bool Equals(Workman workman)
{
if(Object.ReferenceEquals(workman, null))
return false;
if(this.GetType() != workman.GetType())
return false;
return (LastName == workman.LastName);
}
public override int GetHashCode()
{
return LastName.GetHashCode();
}
public static bool operator ==(Workman lhs, Workman rhs)
{
if(Object.ReferenceEquals(lhs, null))
{
if(Object.ReferenceEquals(rhs, null))
{
return true;
}
return false;
}
return lhs.Equals(rhs);
}
public static bool operator !=(Workman lhs, Workman rhs)
{
return !(lhs == rhs);
}
}
现在主要有:
LinkedList test = new LinkedList();
test.Add2( new Workman(new DateTime(), "John", "whatever", 45));
test.Add2( new Workman(new DateTime(), "Mike", "bb", 45));
Workman work = new Workman( new DateTime(), "Mike", "bb", 45 );
if( test.Contains( work ))
{
Console.WriteLine("Contains");
}
这不起作用。当我尝试调试时,在Linkedlist.cs类if( curr.Data == obj)
中的行不会在Workman.cs中输入重写代码。我怎样才能做到这一点?
答案 0 :(得分:1)
您无法覆盖运算符,您只能重载它们。您使用==
参数调用object
运算符重载,而不是使用Workman
参数重新调用新的重载。
我建议你改用object.Equals
,因为你已经覆盖了
if(Equals(cur.Data, obj)
{
return true;
}
答案 1 :(得分:0)
我认为如果添加演员,它会对你有用,因为现在你正在调用对象上的==。 我相信这会奏效:
public bool Contains( Object obj )
{
for( Node curr = Start; curr != null; curr = curr.Next)
{
if(curr.data is workman && obj is workman)
{
if((workman)curr.data == (workman)obj )
{
return true;
}
else
{
return false;
}
}
if( curr.Data == obj )
{
return true;
}
}
return false;
}
我不是100%肯定所以请告诉我它是否对你有所帮助。 感谢。