替代在 NET 2.0 中的字符串中添加空格?

Alternative to adding spaces in strings in NET 2.0?

我正在创建一个服务器-客户端模型,由于客户端开发环境的性质,我不得不使用 .NET 2.0 作为我的框架。

撇开介绍不谈,假设我希望控制台输出一个新连接是在特定时间从特定 IP 地址建立的。我会写:

Console.Writeline("New connection: " +
                  client.endpoint.ToString() + " " + DateTime.Now.ToString());

我想知道这条线路是否有替代方案。其中一些行变得很长,我觉得有点凌乱。

如果您将大量字符串附加在一起,我建议您在 .Net Framework 中使用 StringBuilder class。这将提高性能。

要添加空格,您可以将变量定义为 string separator = " "; 并使用它来创建字符串。

使用 StringBuilder 创建字符串后,您可以将其写入控制台或根据需要执行其他操作。

您可以使用 Console.WriteLine() overloads 之一。它并没有节省太多,但也许它更自然地将语句分成多行,例如:

Console.WriteLine("New connection: {0} {1}", 
                  client.endpoint, 
                  DateTime.Now);

您还可以探索 Trace class. You can configure the Trace options to always output the DateTime so you'd be able to skip that parameter. Then, you can add a ConsoleTraceListener 以将这些 Trace 消息写入控制台。使用这种方法,你会做类似的事情:

Trace.TraceInformation("New connection: {0}", client.endpoint);

您可以使用 String.Format,这会使字符串更易读。它不能完全回答您的问题,但仍然可以。你这样使用它:

String s = String.Format("New connection: {0} {1}.", client.endpoint.ToString(), DateTime.Now.ToString());

使用 Console.WriteLine,您可以这样做:

Console.WriteLine("New connection: {0} {1}.", client.endpoint.ToString(), DateTime.Now.ToString());

一个简单的解决方案可能是创建辅助方法,该方法将采用字符串类型的无限参数(Arguments),然后使用 string.Join() 方法在将文本写入屏幕之前组合和格式化文本:

static void ConsoleLog(params string[] data)  
{  
    Console.WriteLine(string.Join(" ", data));  
}

然后使用这个方法:

ConsoleLog("New connection:", client.endpoint.ToString(), DateTime.Now.ToString());

或者为了更容易 read/edit:

ConsoleLog(
    "New connection:",
    client.endpoint.ToString(),
    DateTime.Now.ToString()
    );