Equals方法有两个问题:首先,如果另一个对象不是类型,它会抛出异常
Issue
,这对大多数开发人员来说是一种意想不到的行为。其次,如果重写Equals,则应始终重写GetHashcode。重要的是,GetHashcode为Equals返回true的两个变量提供相同的结果。您还可以实现
IEquatable<Issue>
让你的代码更有表现力,因为每个人都可以看到,这个类是为了与其他问题进行比较。代码可能如下所示:
public class Issue : IEquatable<Issue>
{
public string Severity { get; set; }
public string Line { get; set; }
public string Type { get; set; }
public string Component { get; set; }
public string Location { get; set; }
public string Status { get; set; }
public BenchmarkCompareResult BenchmarkCompareResult { get; set; }
public override bool Equals(object obj)
{
if(obj is Issue issue)
{
return Equals(issue);
}
return false;
}
public bool Equals(Issue iusse)
{
if(issue is null)
{
return false;
}
return Severity == issue.Severity && Line == issue.Line && Type == issue.Type
&& Component == issue.Component && Location == issue.Location && Status == issue.Status;
}
public override int GetHashCode()
{
// compute the hashcode of a value tuple containing all relevant properties
return (Severity,Line,Type,Component,Location,Status).GetHashCode();
}
}