[英]C# HashSet does not contain only unique objects of the type. Why?
這是我的課。
public class Report
{
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Lat { get; set; }
public string Long { get; set; }
public string Type { get; set; }
public DateTime CreateDate { get; set; }
public override bool Equals(object obj)
{
if (obj == null)
return false;
var y = obj as Report;
if (y == null)
return false;
return
this.Name == y.Name &&
this.Long == y.Long &&
this.Lat == y.Lat;
}
public override int GetHashCode()
{
return (this.Name + this.Long + this.Lat).GetHashCode();
}
}
所以這是我的代碼,當我創建一個新的 HashSet 時,不知何故會出現非唯一值? 有任何想法嗎? 看起來我的帖子主要是代碼,所以我需要添加更多細節。
我正在使用此方法創建在 HashSet 中傳遞的對象(這是一個僅用於測試目的的控制台應用程序,沒什么特別的)
static Report CreateReport(dynamic report)
{
var result = new Report();
result.City = report.city.ToString();
result.Name = report.name.ToString();
result.Country = report.country.ToString();
result.Long = report.@long.ToString();
result.Lat = report.lat.ToString();
result.Type = report.type.ToString();
result.CreateDate = DateTime.Now;
return result;
}
您是否嘗試過使用IEqualityComparer<T>
其中T
是Report
?
public class ReportComparer : IEqualityComparer<Report>
{
public override bool Equals(object obj)
{
if (obj == null)
return false;
var y = obj as Report;
if (y == null)
return false;
return
this.Name == y.Name &&
this.Long == y.Long &&
this.Lat == y.Lat;
}
public int GetHashCode(Report obj)
{
return (this.Name + this.Long + this.Lat).GetHashCode();
}
}
然后用它實例化你的HashSet
:
HashSet<Report> reports = new HashSet<Report>(new ReportComparer())
文檔:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.