1

I'm at a loss. I have a Dictionary object with String keys. The objects are of a custom type I have. This example throws an InvalidCastException:

MyObject temp;
if(Dict.TryGetValue("abc", out temp)) //exception

If I instead use "ContainsKey", I still get an InvalidCastException:

if(Dict.ContainsKey("abc")) //exception

In both cases, if I put a watch on Dict["abc"], I get the value that I want from the Dictionary. The Exception details provide no extra information.

I tried putting together a small code sample that replicates this situation, but my code samples work perfectly. I don't know how to provide a code sample for this problem.

Why would I get an InvalidCastException when checking for the existence of a key in a Dictionary? Why does ContainsKey even need to do any casting in its implementation? How do I fix this?

4

1 回答 1

0

好吧,我可以想出一种重现它的方法,但它是否是这里出了问题是不可能的:

using System;
using System.Collections.Generic;

public class Test
{
    static void Main()
    {
        var dictionary = new Dictionary<string, string>(new BadComparer());
        string temp;
        dictionary["bad"] = "oops"; // Fine...
        dictionary.TryGetValue("bad", out temp); // Bang!
    }    
}

class BadComparer : IEqualityComparer<string>
{
    public int GetHashCode(string x)
    {
        return x.GetHashCode();
    }

    public bool Equals(string x, string y)
    {
        // Bang!
        ((BadComparer) (object) x).ToString();
        return x.Equals(y);
    }
}

请注意,这确实在异常中提供了相关信息:

Unhandled Exception: System.InvalidCastException: Unable to cast object of type
'System.String' to type 'BadComparer'.
   at BadComparer.Equals(String x, String y)
   at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
   at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
   at Test.Main()
于 2012-02-24T17:09:28.133 回答