1

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

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

4

2 回答 2

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));            
} 
于 2012-08-30T12:44:12.653 回答
0

例外是指出您缺少演员表。我在测试项目中复制了您的代码,但无法重现您的错误。尝试使用x.Key.ToString()x.Value.ToString()。我发现的唯一一件事是 Dictionary 为空时引发的错误: sb.ToString(0, sb.Length - 1)when lenght is zero is not working

于 2012-08-30T13:16:41.780 回答