我创建了一个IDictionary
扩展名,用于将IDictionary Exception.Data
值写入字符串。
扩展代码:
public static class DictionaryExtension
{
public static string ToString<TKey, TValue>(this IDictionary<TKey, TValue> source, string keyValueSeparator, string sequenceSeparator)
{
if (source == null)
throw new ArgumentException("Parameter source can not be null.");
return source.Aggregate(new StringBuilder(), (sb, x) => sb.Append(x.Key + keyValueSeparator + x.Value + sequenceSeparator), sb => sb.ToString(0, sb.Length - 1));
}
}
当我在Exception.Data.ToString("=", "|")
上使用此扩展时出现错误
The type arguments cannot be inferred from the usage.
知道如何解决这个问题吗?
答案 0 :(得分:7)
Exception.Data
的类型为IDictionary
,而不是IDictionary<TKey, TValue>
。
您需要将扩展方法更改为:
public static string ToString(this IDictionary source, string keyValueSeparator,
string sequenceSeparator)
{
if (source == null)
throw new ArgumentException("Parameter source can not be null.");
return source.Cast<DictionaryEntry>()
.Aggregate(new StringBuilder(),
(sb, x) => sb.Append(x.Key + keyValueSeparator + x.Value
+ sequenceSeparator),
sb => sb.ToString(0, sb.Length - 1));
}
答案 1 :(得分:0)
异常表明你缺少演员。
我在测试项目中复制了您的代码,但我无法重现您的错误。
尝试使用x.Key.ToString()
和x.Value.ToString()
。
我发现的唯一一件事就是当Dictionary为空时出现错误:
当长度为零时,sb.ToString(0, sb.Length - 1)
无法正常工作