-1

有谁知道如何检查一个类在哈希表中是否包含完全相同的值?就像下面的示例代码一样,即使我将 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";


        }
    }
4

1 回答 1

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:http: 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. //msdn.microsoft.com/en-us/library/xfhwa508.aspx

于 2013-08-27T06:58:30.503 回答