【发布时间】: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<string>。我怎样才能使它更通用?
另外,我在想,也许我不应该在上面工作
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<K, V>,但当它碰巧是一个IEnumerable<T>时,它会打印出每个价值? -
不要编写只检查内部类型是否为
List的泛型方法。如果您想这样做,只需将参数设置为List<T>即可。如果您需要支持Dictionary,请为其创建单独的重载。 -
嗨阿德里安班克斯,后者是我的目标。改进 ToDelimitedStr 只是解决方案。一开始,我试图找到一种方法来覆盖 IEnumerable
.ToString(),因为默认版本输出像'System.Collections.Generic.List`1[System.String]',但我喜欢打印出每个值。
标签: c# dictionary tostring