IDictionary to string

大城市里の小女人 提交于 2021-02-08 06:39:39

问题


I have created an IDictionary extension to write IDictionary Exception.Data values to a string.

The extension code:

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));           
    }
}

When I use this extension on Exception.Data.ToString("=", "|") I get error

The type arguments cannot be inferred from the usage.

Any idea how to solve this?


回答1:


Exception.Data is of type IDictionary, not IDictionary<TKey, TValue>.

You need to change your extension method to this:

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));            
} 



回答2:


The exception is pointing that you are missing a cast. I copied your code in a test project but I was unable to reproduce your error. Try using x.Key.ToString() and x.Value.ToString(). The only thing I found is an error raised when Dictionary is empty: sb.ToString(0, sb.Length - 1) when lenght is zero is not working



来源:https://stackoverflow.com/questions/12197089/idictionary-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!