简体   繁体   中英

C# override Dictionary ContainsKey

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM