![](/img/trans.png)
[英]How to use a static import for java.util.Arrays.toString?
[英].NET equivalent of java.util.Arrays.toString(…) methods in Java
In Java, the java.util.Arrays
class have several static toString(...)
methods that take an array and return its string representation (ie the string representation of the contents of the array separated by commas and the whole representation enclosed in square括號 - 例如“[1, 2, 3]”)。
.NET 中是否有等效的方法/功能?
我正在尋找一種無需手動構建循環/方法來遍歷數組的 for 方法。
String.Join方法。
[您需要自己添加方括號]
嘗試這個。 它不會處理 NULL 值,但它適用於值類型和引用類型。 因為它是一種擴展方法,您可以在任何數組實例上調用 .ToElementString() 。
public static string ToElementString<T>(this T[] array) {
var middle = array.Select(x => x.ToString().Aggregate((l,r) => l+","+r);
return "[" + middle + "]";
}
這是一個使用構建器的版本,並且可能會更有效率(只有分析器肯定知道)。 它還將正確處理 null 值。
public static string ToElementString<T>(this T[] array) {
var builder = new StringBuilder();
builder.Append('[');
for(int i =0; i < array.Length; i++ ) {
if ( i > 0 ) {
builder.Append(',');
}
builder.Append(array[i]);
}
builder.Append(']');
return builder.ToString();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.