34

A System.Collections.Generic.Dictionaryis throwing KeyNotFoundException,但我看不到应该缺少哪个键。我如何确定这一点?

4

7 回答 7

23

自定义异常:

class WellknownKeyNotFoundException : KeyNotFoundException
{
    public WellknownKeyNotFoundException(object key, string message)
        : this(key, message, null) { }

    public WellknownKeyNotFoundException(object key, string message, Exception innerException)
        : base(message, innerException)
    {
        this.Key = key;
    }

    public object Key { get; private set; }
}

方便的扩展方法:

public TValue GetValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
{
    try
    {
        return dic[key];
    }
    catch (KeyNotFoundException ex)
    {
        throw new WellknownKeyNotFoundException((object)key, ex.InnerException);
    }
}

用法:

var foo = new Foo();
var bar = new Bar();

IDictionary<Foo, Bar> dic = new Dictinary<Foo, Bar>
{
    { foo, bar }
};

try
{
    dic.GetValue(foo);
}
catch (WellknownKeyNotFoundException ex)
{
    var key = (Foo)ex.Key;
    Assert.AreEqual(foo, key); // should be
}
于 2011-08-29T12:28:34.303 回答
17

没有办法从异常中看出这一点。您需要为此实施自己的解决方案。

于 2011-08-29T12:20:24.633 回答
6

如果您可以自定义声明字典的实现,则可以轻松地将 System.Collections.Generic.Dictionary 替换为自定义类型,引发更好的 KeyNotFoundException。虽然这与 abatishchev 的答案相似,但我不喜欢他介绍的扩展方法,因为这意味着我们有两种不同的方法来实现完全相同的事情。如果可能,应该避免这种情况。我通过使用“NiceDictionary”解决了这个问题,它可以像原来用作基类的字典一样使用。实现几乎是微不足道的:

/// <summary>
/// This is a nice variant of the KeyNotFoundException. The original version 
/// is very mean, because it refuses to tell us which key was responsible 
/// for raising the exception.
/// </summary>
public class NiceKeyNotFoundException<TKey> : KeyNotFoundException
{
    public TKey Key { get; private set; }

    public NiceKeyNotFoundException(TKey key, string message)
        : base(message, null)
    {
        this.Key = key;
    }

    public NiceKeyNotFoundException(TKey key, string message, Exception innerException)
        : base(message, innerException)
    {
        this.Key = key;
    }
}

/// <summary>
/// This is a very nice dictionary, because it throws a NiceKeyNotFoundException that
/// tells us the key that was not found. Thank you, nice dictionary!
/// </summary>
public class NiceDictionary<TKey, TVal> : Dictionary<TKey, TVal>
{
    public new TVal this[TKey key]
    {
        get
        {
            try
            {
                return base[key];
            }
            catch (KeyNotFoundException knfe)
            {
                throw new NiceKeyNotFoundException<TKey>(key, knfe.Message, knfe.InnerException);
            }
        }
        set
        {
            try
            {
                base[key] = value;
            }
            catch (KeyNotFoundException knfe)
            {
                throw new NiceKeyNotFoundException<TKey>(key, knfe.Message, knfe.InnerException);
            }
        }
    }
}

如前所述,您可以像使用原始字典一样使用它。由于重写的数组运算符([]),它神奇地起作用。

于 2013-03-04T09:16:53.793 回答
3

你不能只看异常。抛出异常时,您必须闯入调试器( Visual Studio 中的Debug -> Exceptions... )并查看已访问的键。或者,您可以在代码中捕获异常并将其打印出来(例如到控制台)。

于 2011-08-29T12:20:44.697 回答
0

使用调试器(如果需要,请检查 Debug->Exceptions 中的 ThrowOnCatch)并查看

于 2011-08-29T12:20:45.507 回答
-1

System.Collections.Generic.KeyNotFoundException 已被抛出

如果您将 DotNet Core 与 Xamarin Studio 一起使用并且收到此错误,您可以检查密钥是否存在,并满足以下条件:

if (Application.Current.Properties.ContainsKey("userCredentials")) {
    //now process...
}
于 2020-01-04T18:27:50.530 回答
-1

您会认为他们可以将尝试的密钥添加到 exception.data

这就是我所做的

        public static void SetGlobals()
    {
        string currentKey = "None";
        try
        {
            currentKey = "CurrentEnvironment";
            Globals.current_environment = Settings[currentKey];
            currentKey = "apiUrl";
            Globals.api_url = Settings[currentKey];
            currentKey = "whatever";
            Globals.whatever= Settings[currentKey];

            if (AppDomain.CurrentDomain.GetData(".devEnvironment") as bool? == true)
                Globals.api_url = "http://localhost:59164/api";
        }
        catch(KeyNotFoundException)
        {
            DBClass.logEvent("Error", "AppSettings", "Missing Setting: " + currentKey);
        }
    }
于 2020-09-24T21:19:52.833 回答