【问题标题】:How to check hashtable contains a correct class [closed]如何检查哈希表包含正确的类[关闭]
【发布时间】:2013-08-27 06:39:49
【问题描述】:

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


        }
    }

【问题讨论】:

  • 它会做,首先你检查哈希是否包含color,这在任何地方都没有提到。然后你返回 good 这只是一个没有相关性的新商品,并且不知道 Good 是一个颜色
  • 首先准备一个可编译代码。这样你的问题会更有意义。
  • @Sayse 抱歉,我忘了用好的替换颜色,已编辑

标签: c# asp.net web-services hashtable


【解决方案1】:

(您的问题仍然不清楚。但我会尝试猜测)这是因为您的对象的引用被比较了。您应该为您的对象定义相等性。例如,

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&lt;TKey, TValue&gt;, it must not change in any way that affects its hash value. http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

【讨论】:

  • 实现equals和hashtable后,就可以了!谢谢
猜你喜欢
  • 2017-04-13
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
  • 2013-11-22
  • 2011-04-19
  • 1970-01-01
  • 2014-04-06
  • 2015-03-28
相关资源
最近更新 更多