【发布时间】:2018-09-28 18:52:08
【问题描述】:
我有一个Configuration 类,其中包含许多设置。一个简单的例子:
class Configuration
{
public string Name { get; set; }
public string Url { get; set; }
public string Password { get; set; }
//There are about 20 of these
}
我想为调用者提供从字符串字典填充此对象的能力,如下所示:
static Configuration CreateFromDictionary(Dictionary<string, string> dict)
{
try
{
return new Configuration
{
Name = dict["Name"],
Url = dict["Url"],
Password = dict["Password"]
}
}
catch(KeyNotFoundException exception)
{
throw new ArgumentException("Unable to construct a Configuration from the information given.");
}
}
这很有效,除了它是一个全有或全无的转换。如果调用者提供的字典大部分都很好,但其中一个条目拼写错误,则转换失败并出现异常。
我希望能够提供更好的异常消息,告诉调用者 哪个 键未找到。似乎有点重要。但我无法从KeyNotFoundException 检索该信息。
我可以编写代码来一次解析字典一行并单独检查每个键,但这似乎真的很痛苦。有没有什么办法可以通过ContainsKey 或TryGetValue 一次一行地从异常信息中判断未找到哪个键?
【问题讨论】:
-
在开始时收集值。
标签: c# .net exception-handling