【问题标题】:How to print a custom string when a value is null, using .NET's string.Join method?如何在值为 null 时使用.NET 的 string.Join 方法打印自定义字符串?
【发布时间】:2014-05-27 07:57:06
【问题描述】:

我有以下课程:

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 + "]";
    }
}

我重写了 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)); 

这将在屏幕上打印 '[1, 2], [10, 20],'。问题是我想以某种方式打印'[1, 2], [10, 20], 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";
}

所以,现在如果我调用 string.Join 方法,可以这样写:

Point[] points = new Point[] { point1, point2, new Point(true) };

我得到了想要的输出 '[1, 2], [10, 20], null]',但正如我所写的那样,我认为这是丑陋且不正确的,所以有人可以帮我解决这个问题吗?

我真的需要使用带有 Point 对象数组的 string.Join 方法。

【问题讨论】:

  • @Mohamed 阅读顶部的代码 - Point 是 OP 编写的

标签: c# string join printing null


【解决方案1】:

你不能改变Join如何解释null,所以:首先改变有null的事实;这行得通:

Console.WriteLine(string.Join(", ", points.Select(Point.Render)));

Point.Render 在哪里:

internal static string Render(Point point)
{
    return point == null ? "null" : point.ToString();
}

但是,我想知道这是否更可取:

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();
}

与:

Console.WriteLine(Point.Render(points));

或者,如果您将其设为扩展方法:

Console.WriteLine(points.Render());

【讨论】:

  • 我添加了一个扩展方法,就像你提供的静态方法一样(我只是在第一个方法参数前添加了'this'关键字)然后使用这样的方法:Console.WriteLine( string.Join(", ", points.Select(point => point.Render())));它完全按照我的意愿工作。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多