Yul*_*ian 4 c# printing string null join
我有以下课程:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
public Point(int x, int y)
{
X = x;
Y = y;
}
public override string ToString()
{
return "[" + X + ", " + Y + "]";
}
}
Run Code Online (Sandbox Code Playgroud)
我已经重写了 ToString 方法,因此,如果尝试将 Point 对象的值存储在字符串中,它可能具有以下格式:“[X, Y]”。
假设我有一个点数组,我想打印它们,用逗号分隔。
Point point1 = new Point(1, 2);
Point point2 = new Point(10, 20);
Point[] points = new Point[] { point1, point2, null };
Console.WriteLine(string.Join<Point>(", ", points));
Run Code Online (Sandbox Code Playgroud)
这将在屏幕上打印“[1, 2], [10, 20],”。问题是我想以某种方式打印 '[1, 2], [10, 20], null' - 意思是,当我有 null 值时打印 'null'。
我想到了一个解决方法,但它在设计方面确实很丑陋且不正确。我在 Point 类中添加了以下代码:
private bool isNull;
public Point(bool isNull = false)
{
this.isNull = isNull;
}
public override string ToString()
{
if (!isNull)
{
return "[" + X + ", " + Y + "]";
}
return "null";
}
Run Code Online (Sandbox Code Playgroud)
因此,现在如果我调用 string.Join 方法,请编写以下内容:
Point[] points = new Point[] { point1, point2, new Point(true) };
Run Code Online (Sandbox Code Playgroud)
我得到了所需的输出 '[1, 2], [10, 20], null]',但正如我所写,我认为这是丑陋且不正确的,所以有人可以帮助我吗?
我确实需要将 string.Join 方法与 Point 对象数组一起使用。
你无法改变 的Join解释方式,所以:首先null改变存在的事实;null这有效:
Console.WriteLine(string.Join(", ", points.Select(Point.Render)));
Run Code Online (Sandbox Code Playgroud)
哪里Point.Render:
internal static string Render(Point point)
{
return point == null ? "null" : point.ToString();
}
Run Code Online (Sandbox Code Playgroud)
但是,我想知道这是否更好:
public static string Render(IEnumerable<Point> points)
{
if (points == null) return "";
var sb = new StringBuilder();
foreach(var point in points)
{
if (sb.Length != 0) sb.Append(", ");
sb.Append(point == null ? "null" : point.ToString());
}
return sb.ToString();
}
Run Code Online (Sandbox Code Playgroud)
和:
Console.WriteLine(Point.Render(points));
Run Code Online (Sandbox Code Playgroud)
或者,如果您将其设为扩展方法:
Console.WriteLine(points.Render());
Run Code Online (Sandbox Code Playgroud)