我想要一个函数,我可以调用它来替代.ToString(),它将显示集合的内容.
我试过这个:
public static string dump(Object o) {
if (o == null) return "null";
return o.ToString();
}
public static string dump<K, V>(KeyValuePair<K, V> kv) {
return dump(kv.Key) + "=>" + dump(kv.Value);
}
public static string dump<T>(IEnumerable<T> list) {
StringBuilder result = new StringBuilder("{");
foreach(T t in list) {
result.Append(dump(t));
result.Append(", ");
}
result.Append("}");
return result.ToString();
}
Run Code Online (Sandbox Code Playgroud)
但第二次超载永远不会被调用.例如:
List<string> list = new List<string>();
list.Add("polo");
Dictionary<int, List<string>> dict;
dict.Add(1, list);
Console.WriteLine(dump(dict));
Run Code Online (Sandbox Code Playgroud)
我期待这个输出:
{1=>{"polo", }, }
Run Code Online (Sandbox Code Playgroud)
实际发生的是:dict被正确解释为a IEnumerable<KeyValuePair<int, List<string>>>,因此调用第3个重载.
第3次重载调用KeyValuePair上的转储>.这应该(?)调用第二个重载,但它没有 - 它调用第一个重载.
所以我们得到这个输出:
{[1=>System.Collections.Generic.List`1[System.String]], }
Run Code Online (Sandbox Code Playgroud)
它是从KeyValuePair的.ToString()方法构建的.
为什么不调用第二个重载?在我看来,运行时应该具有识别具有完整通用参数的KeyValuePair所需的所有信息并调用该信息.
泛型是编译时的概念,而不是运行时.换句话说,类型参数在编译时被解析.
在你的foreach中,你打电话,dump(t)而t是T型.但是除了它是一个之外,在这一点上没有任何关于T的知识Object.这就是调用第一个重载的原因.
(更新)正如其他答案中提到的,问题是编译器不知道 typeV实际上是 a List<string>,所以它只是转到dump(object).
一种可能的解决方法是在运行时检查类型。Type.IsGenericType会告诉您变量的类型是否具有泛型,并Type.GetGenericArguments给出这些泛型的实际类型。
因此,您可以编写一个dump接收对象并忽略任何泛型信息的方法。请注意,我使用的是System.Collections.IEnumerable接口而不是System.Collections.Generics.IEnumerable<T>.
public static string dump(Object o)
{
Type type = o.GetType();
// if it's a generic, check if it's a collection or keyvaluepair
if (type.IsGenericType) {
// a collection? iterate items
if (o is System.Collections.IEnumerable) {
StringBuilder result = new StringBuilder("{");
foreach (var i in (o as System.Collections.IEnumerable)) {
result.Append(dump(i));
result.Append(", ");
}
result.Append("}");
return result.ToString();
// a keyvaluepair? show key => value
} else if (type.GetGenericArguments().Length == 2 &&
type.FullName.StartsWith("System.Collections.Generic.KeyValuePair")) {
StringBuilder result = new StringBuilder();
result.Append(dump(type.GetProperty("Key").GetValue(o, null)));
result.Append(" => ");
result.Append(dump(type.GetProperty("Value").GetValue(o, null)));
return result.ToString();
}
}
// arbitrary generic or not generic
return o.ToString();
}
Run Code Online (Sandbox Code Playgroud)
也就是说:a) 迭代集合,b) 键值对显示key => value,c) 任何其他对象只调用ToString。有了这个代码
List<string> list = new List<string>();
list.Add("polo");
Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>() ;
dict.Add(1, list);
Console.WriteLine(dump(list));
Console.WriteLine(dump(dict.First()));
Console.WriteLine(dump(dict));
Run Code Online (Sandbox Code Playgroud)
你会得到预期的输出:
{marco, }
1 => {marco, }
{1 => {marco, }, }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
569 次 |
| 最近记录: |