.net 当抛出KeyNotFoundException时,我如何看到哪个键没有找到?

gz5pxeao  于 2022-12-30  发布在  .NET
关注(0)|答案(8)|浏览(122)

一个System.Collections.Generic.Dictionary抛出了KeyNotFoundException,但是我看不到哪个键应该丢失了,我该如何判断呢?

afdcj2ne

afdcj2ne1#

自定义例外:

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
}
6ss1mwsb

6ss1mwsb2#

没有办法区分这和异常,您需要实现自己的解决方案。

368yc8dk

368yc8dk3#

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

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

正如所说,你可以像使用原来的字典一样使用它。它神奇地工作,因为覆盖了数组操作符([])。

ds97pgxw

ds97pgxw4#

你不能只看异常。你必须在抛出异常时进入调试器(Visual Studio中的 *Debug -〉Exceptions... *),看看哪个键被访问了。或者,你可以在代码中捕获异常并打印出来(例如打印到控制台)。

qnyhuwrf

qnyhuwrf5#

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

pnwntuvh

pnwntuvh6#

我用了这个延伸法

internal static class KeyNotFoundExceptionExtensions
{
    public static string GetKeyValue(this KeyNotFoundException ex)
    {
        var match = Regex.Match(ex.Message, @"'(.*?)'");
        if (match.Success)
            return match.Groups[1].Value;

        throw ex;
    }
}
lrl1mhuk

lrl1mhuk7#

已引发系统.集合.泛型.KeyNotFoundException
如果您在使用DotNet Core和Xamarin Studio时遇到此错误,您可以使用以下条件检查密钥是否存在:

if (Application.Current.Properties.ContainsKey("userCredentials")) {
    //now process...
}
7kjnsjlb

7kjnsjlb8#

您可能认为他们可以将尝试的密钥添加到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);
        }
    }

相关问题