有谁知道如何检查一个类在哈希表中包含完全相同的值?就像下面的示例代码一样,即使我将item1和item2设置为哈希表中的一个,它仍然会返回“未找到”消息。
public class WebService2 : System.Web.Services.WebService
{
public class Good
{
public string item1="address";
public string item2 ="postcode";
}
[WebMethod]
public string findhome()
{
Dictionary<Color, string> hash = new Dictionary<Color, string>();
Good good = new Good();
hash.Add(new Good() { item1 = "address", item2 = "postcode" },"home");
if (hash.ContainsKey(good))
{
return (string)hash[good];
}
return "not supported";
}
}
答案 0 :(得分:0)
(您的问题仍然不明确。但我会尝试猜测)这是因为您的对象的引用会被比较。您应该为对象定义相等性。例如,
public class Good
{
public string item1 = "address";
public string item2 = "postcode";
public override int GetHashCode()
{
return (item1+item2).GetHashCode();
}
public override bool Equals(object obj)
{
if (!(obj is Good)) return false;
if (obj == null) return false;
var good = obj as Good;
return good.item1==item1 && good.item2==item2;
}
}
PS: As long as an object is used as a key in the Dictionary<TKey, TValue>, it must not change in any way that affects its hash value.
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx