【问题标题】:Dictionary<K,V>.ToString() more generic implementationDictionary<K,V>.ToString() 更通用的实现
【发布时间】:2014-03-31 13:52:45
【问题描述】:

我有来自Most efficient Dictionary.ToString() with formatting? 的这个问题,但我的问题是如果 V 是 List,如何使它工作。现在我的解决方案是, 改变

itemString.AppendFormat(format, item.Key, item.Value);

itemString.AppendFormat(format, item.Key, item.Value.ToDelimitedStr());

这是 ToDelimitedStr 的代码:

    public static string ToDelimitedStr<T>(this T source)
    {
        // List<string> 
        if (source is IList &&
            source.GetType().IsGenericType)
        {
            Type t1 = source.GetType().GetGenericArguments()[0];
            if (t1.Name == "String")
                ((IEnumerable<string>)source).ToDelimitedString();
        }
        return source.ToString();
    }

仅适用于List&lt;string&gt;。我怎样才能使它更通用? 另外,我在想,也许我不应该在上面工作

public string DictToString<T, V>(IEnumerable<KeyValuePair<T, V>> items, string format)

我应该创建一个新版本,例如

public string DictListToString<T, List<V>>(IEnumerable<KeyValuePair<T, List<V>>> items, string format)

怎么样?

非常感谢

韦斯

【问题讨论】:

  • 您是在问如何改进您的 ToDelimitedStr 方法,或者当 V 可以是任何东西时如何处理 Dictionary&lt;K, V&gt;,但当它碰巧是一个 IEnumerable&lt;T&gt; 时,它会打印出每个价值?
  • 不要编写只检查内部类型是否为List 的泛型方法。如果您想这样做,只需将参数设置为 List&lt;T&gt; 即可。如果您需要支持 Dictionary,请为其创建单独的重载。
  • 嗨阿德里安班克斯,后者是我的目标。改进 ToDelimitedStr 只是解决方案。一开始,我试图找到一种方法来覆盖 IEnumerable.ToString(),因为默认版本输出像'System.Collections.Generic.List`1[System.String]',但我喜欢打印出每个值。

标签: c# dictionary tostring


【解决方案1】:

使用string.Join

return string.Join("," , (IList<T>)source); 

我认为如果您为ToDelimitedStr 添加一个以IEnumerable&lt;T&gt; 作为参数的过载会更容易,那么您不需要该类型检查:

public static string ToDelimitedStr<T>(this IEnumerable<T> source)
{
     return string.Join(",", source);
}

【讨论】:

    【解决方案2】:

    使用IEnumerable 并在项目上调用ToString

    public static string ToDelimitedStr<T>(this T source)
    {
        // Will work for ANY IEnumerable
        if (source is IEnumerable)     // <----------------
        {
            IEnumerable<string> items =
               ((IEnumerable)source).OfType<object>()
                                    .Select(o => o.ToString());
            // convert items to a single string here...
            return string.Join(", ", items);
        }
        return source.ToString();
    }
    

    【讨论】:

    • @Selman22 没有采用 IEnumerable 的重载 - 只有 IEnumerable&lt;string&gt;IEnumerable&lt;T&gt;。在这种情况下,集合的基础类型是未知的。它可以通过反射提取,但在这种情况下是不必要的。
    猜你喜欢
    • 1970-01-01
    • 2011-04-08
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    相关资源
    最近更新 更多