我正在学习C#& amp;有以下代码。
private static Policy ConstructNode(Policy policy, Dictionary<string, dynamic> noticeDictionary)
{
Policy policy = new Policy();
foreach (var pair in noticeDictionary)
{
policy.Emails = pair.Value; // HERE, I GET RUNTIME ERROR
...
}
return policy;
}
Emails
类中的Policy
类型为Dictionary<string, uint>
&amp; pair.Value
包含Dictionary<string, dynamic>
Noticedictionary如下所示:
noticeDictionary.Add("Notice", JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(val));
val包含JSON字符串,该字符串可以包含带字符串键的字符串或int值。
如何投射它们以免它出错?
答案 0 :(得分:3)
Dictionary<string, uint> Converted = noticeDictionary
// Next steps converts to an IEnumerable<anonymoustype<string,uint>>
.Select(kvp=> new { key = kvp.Key , val = (uint)kvp.Value})
// Now that we have strongly typed data in enumerable form, get it back into a dictionary
.ToDictionary(item=>item.Key,item=>item.Value);
关于你的第二个问题(如果类型是混合的,我如何转换为无错误),这是不可能的,但如果字符串只是编码uint你可以通过修改选择值来处理这两个
.Select(kvp=> new { key = kvp.Key , val = (kvp.Value is int) ? (kvp.Value) : uint.Parse((string)kvp.Value)}) // This is untested, let me know if you have trouble