Dictionary.ContainsKey return False, but a want True

前端 未结 12 1000
野性不改
野性不改 2020-12-03 10:16
namespace Dic
{
public class Key
{
    string name;
    public Key(string n) { name = n; }
}

class Program
{
    static string Test()
    {
        Key a = new Key(         


        
12条回答
  •  情话喂你
    2020-12-03 11:14

    If you do not have the ability to override equality operators/Equals/GetHashCode as others have mentioned (as in, you do not control the source code of the object), you can provide an IEqualityComparer implementation in the constructor of the dictionary to perform your equality checks.

    class KeyComparer : IEqualityComparer
    {
        public bool Equals(Key x, Key y)
        {
            return x.Name == y.Name;
        }
    
        public int GetHashCode(Key obj)
        {
            return obj.Name.GetHashCode();
        }
    }
    

    As it stands, your Key is a reference object, so equality is only determined on reference unless you tell the world (or the dictionary) otherwise.

提交回复
热议问题