-1

クラスにハッシュテーブル内にまったく同じ値が含まれていることを確認する方法を知っている人はいますか? 以下のコード例のように、アイテム1とアイテム2をハッシュテーブルと同じに設定しても、「見つかりません」というメッセージが返されます。

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: 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

于 2013-08-27T06:58:30.503 に答える