C# override Dictionary ContainsKey

痴心易碎 提交于 2019-12-19 11:44:12

问题


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;}
}

回答1:


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.




回答2:


You don't need to override ContainsKey - you need to either override Equals and GetHashCode in someObj (which should be renamed to conform to .NET naming conventions, btw) or you need to pass an IEqualityComparer<someObj> to the Dictionary<,> constructor. Either way, that code is used to compare keys (and obtain hash codes from them).

Basically you need to make Equals determine equality, and make GetHashCode return the same code for equal objects and ideally different codes for different objects - see Eric Lippert's article on GetHashCode for more details.

Also, you should consider making someObj immutable: mutable dictionary keys are generally a bad idea, as if you modify the key in a hashcode-sensitive way after using it as a key within the dictionary, you won't be able to find it again. If the point of your custom type really is to be a key, then just make it immutable.

For simplicity, you should also consider making someObj implement IEquatable<someObj>, and also think about whether it would be appropriate to be a struct instead of a class. If you implement IEquatable<someObj> you should also override object.Equals in a consistent way. Usually the object.Equals implementation will just call the most strongly-typed IEquatable<T>.Equals implementation.



来源:https://stackoverflow.com/questions/21602828/c-sharp-override-dictionary-containskey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!