打印任何类型的数组和列表的常用方法 [英] Common method for printing arrays and lists of any types
问题描述
每当我调试一段涉及整数或整数,双精度,字符串等的数组或列表的代码时,我有时宁愿打印它们。我要做的是为不同类型编写重载的printArray / printList方法。
Whenever I am debugging a piece of code which involves arrays or lists of ints, doubles, strings, etc/, I prefer printing them over sometimes. What I do for this is write overloaded printArray / printList methods for different types.
例如
我可能有这三种方法可以打印各种类型的数组
I may have these 3 methods for printing arrays of various types
public void printArray(int[] a);
public void printArray(float[] b);
public void printArray(String[] s);
尽管这对我有用,但我仍然想知道是否可以使用通用方法打印任何类型的数组/列表。
Though this works for me, I still want to know whether it is possible to have a generic method which prints arrays/lists of any types. Can this also be extended to array/list of objects.
推荐答案
有用的 String.Join< T>(字符串分隔符,IEnumerable< T>值)
方法。您可以传递任何对象的数组或列表或任何可枚举的集合,因为对象将通过调用 .ToString()
转换为字符串。
There is useful String.Join<T>(string separator, IEnumerable<T> values)
method. You can pass array or list or any enumerable collection of any objects since objects will be converted to string by calling .ToString()
.
int[] iarr = new int[] {1, 2, 3};
Console.WriteLine(String.Join("; ", iarr)); // "1; 2; 3"
string[] sarr = new string[] {"first", "second", "third"};
Console.WriteLine(String.Join("\n", sarr)); // "first\nsecond\nthird"
这篇关于打印任何类型的数组和列表的常用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!