IDictionary到字符串 [英] IDictionary to string

查看:72
本文介绍了IDictionary到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 IDictionary 扩展名,以将 IDictionary Exception.Data 值写入字符串.

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

扩展代码:

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("=","|")上使用此扩展名时,出现错误

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

不能从用法中推断出类型实参.

有什么办法解决这个问题吗?

Any idea how to solve this?

推荐答案

您需要将扩展​​方法更改为此:

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

这篇关于IDictionary到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆