C# 打印任何类型的数组和列表的常用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9655262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:20:39  来源:igfitidea点击:

Common method for printing arrays and lists of any types

c#debugginggenerics

提问by shahensha

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.

每当我调试一段涉及整数、双精度、字符串等数组或列表的代码时,我有时更喜欢将它们打印出来。我为此所做的是为不同类型编写重载的 printArray / printList 方法。

for e.g.

例如

I may have these 3 methods for printing arrays of various types

我可能有这 3 种方法来打印各种类型的数组

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.

虽然这对我有用,但我仍然想知道是否有可能有一个打印任何类型的数组/列表的通用方法。这也可以扩展到对象的数组/列表。

采纳答案by Kirill

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().

有一个有用的String.Join<T>(string separator, IEnumerable<T> values)方法。您可以传递数组或列表或任何对象的任何可枚举集合,因为对象将通过调用.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"

回答by M.Babcock

Arrays and generic lists both implement IEnumerable<T>so just use it as your parameter type.

数组和泛型列表都实现了,IEnumerable<T>所以只需将它用作参数类型。

public void PrintCollection<T>(IEnumerable<T> col)
{
    foreach(var item in col)
        Console.WriteLine(item); // Replace this with your version of printing
}

回答by hago

you can make a generic method like this

你可以做一个这样的通用方法

    public static void print<T>(T[] data)
    {
        foreach (T t in data) {
            Console.WriteLine(t.ToString());
        }
    }

回答by Rohit Sharma

public void printArray<T>(IEnumerable<T> a)
{    
   foreach(var i in a)
   {
        Console.WriteLine(i);
   }
}

回答by Mike Cowan

Here's an extension method appropriate for debugging:

这是一个适合调试的扩展方法:

[Conditional("DEBUG")]
public static void Print<T>(this IEnumerable<T> collection)
{
    foreach(T item in collection)
    {
        Console.WriteLine(item);
    }
}