C#覆盖Dictionary ContainsKey [英] C# override Dictionary ContainsKey

查看:542
本文介绍了C#覆盖Dictionary ContainsKey的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我使用 Dict.ContainsKey 但是由于我总是创建我需要查找的密钥,我总是为ContainsKey(因为hashKey是不同的,我创建的密钥,我想检查所有的时间)$



有人可以建议如何覆盖包含密钥或如何处理在这种情况下比较的密钥?
我的字典看起来像
字典< someObj,int>

 code> public class someObj 
{
public int someobjParam {get; set;}
public int someobjParamTwo {get; set;}
}


解决方案

您不需要覆盖 ContainsKey ,而是指示字典当它应该考虑两个键是相等的。



一种方法是通过实现 IEquatable< someObj> 在你的钥匙班。如果平等的概念在您的应用程序中是全局的,请执行此操作:

  public class someObj:IEquatable< someObj> 
{
public int someobjParam {get; set;}
public int someobjParamTwo {get; set;}

//覆盖GetHashCode()和Equals();例如
//见http://msdn.microsoft.com/en-us/library/ms131190%28v=vs.110%29.aspx
}

另一个是通过实现一个 IEqualityComparer< someObj> 并将其传递到字典构造函数。


I just can't find any proper piece of code to do what i need.

Im using Dict.ContainsKey but due to the fact im always creating the Key i need to look for, i always get false for the ContainsKey (because hashKey is different and im creating the key i want to check all the time).

can someone please advise how to override Contains key or how to handle keys comparing in this situation ? My dictionary Looks like Dictionary<someObj, int>

public class someObj
{
    public int someobjParam {get;set;}
    public int someobjParamTwo {get;set;}
}

解决方案

You don't need to override ContainsKey, but rather instruct the dictionary when it should consider that two keys are equal.

One way to do that is by implementing IEquatable<someObj> in your key class. Do this if the concept of equality is global across your app:

public class someObj : IEquatable<someObj>
{
    public int someobjParam {get;set;}
    public int someobjParamTwo {get;set;}

    // override GetHashCode() and Equals(); for an example
    // see http://msdn.microsoft.com/en-us/library/ms131190%28v=vs.110%29.aspx
}

Another one is by implementing an IEqualityComparer<someObj> and passing it to the dictionary's constructor.

这篇关于C#覆盖Dictionary ContainsKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆