gpt4 book ai didi

c# - C# 中的 "Verbose Dictionary",'override new' this[] 或实现 IDictionary

转载 作者:太空狗 更新时间:2023-10-29 18:19:26 27 4
gpt4 key购买 nike

我想要的只是一本字典,告诉我它找不到哪个键,而不是仅仅说给定的键不存在于字典中

我曾短暂地考虑过用 override new this[TKey key] 做一个子类,但觉得它有点 hacky,所以我已经实现了 IDictionary 接口(interface),并将所有内容直接传递给一个内部字典,唯一的附加逻辑在索引器中:

public TValue this[TKey key]
{
get
{
ThrowIfKeyNotFound(key);
return _dic[key];
}
set
{
ThrowIfKeyNotFound(key);
_dic[key] = value;
}
}
private void ThrowIfKeyNotFound(TKey key)
{
if(!_dic.ContainsKey(key))
throw new ArgumentOutOfRangeException("Can't find key [" + key + "] in dictionary");
}

这是正确/唯一的方法吗? new this[] 真的那么糟糕吗?

最佳答案

听起来很适合扩展方法:

public static class SomeUtilClass {
public static TValue VerboseGetValue<TKey, TValue>(
this IDictionary<TKey, TValue> data, TKey key)
{
TValue result;
if (!data.TryGetValue(key, out result)) {
throw new KeyNotFoundException(
"Key not found: " + Convert.ToString(key));
}
return result;
}
}

这将在您调用 VerboseGetValue 时对所有现有词典起作用,例如:

    var data = new Dictionary<int, string> { { 123, "abc" } };
Console.WriteLine(data.VerboseGetValue(123));
Console.WriteLine(data.VerboseGetValue(456));

关于c# - C# 中的 "Verbose Dictionary",'override new' this[] 或实现 IDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2718948/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com