IDictionary到字符串

时间:2012-08-30 12:41:30

标签: c# extension-methods idictionary

我创建了一个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.

知道如何解决这个问题吗?

2 个答案:

答案 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)无法正常工作