C# 如何格式化字符串

C# 如何格式化字符串,c#,string,windows-phone-8,formatting,format,C#,String,Windows Phone 8,Formatting,Format,在我的应用程序中,我正在确定网络发生的变化。我使用了一些示例代码,但我希望以某种方式格式化生成的字符串 string change = string.Empty; switch (e.NotificationType) { case NetworkNotificationType.InterfaceConnected: change = "Connected to "; bre

在我的应用程序中,我正在确定网络发生的变化。我使用了一些示例代码,但我希望以某种方式格式化生成的字符串

string change = string.Empty;
        switch (e.NotificationType)
        {
            case NetworkNotificationType.InterfaceConnected:
                change = "Connected to ";
                break;
            case NetworkNotificationType.InterfaceDisconnected:
                change = "Disconnected from ";
                break;
            case NetworkNotificationType.CharacteristicUpdate:
                change = "Characteristics changed for ";
                break;
            default:
                change = "Unknown change with ";
                break;
        }

        string changeInformation = String.Format(" {0} {1} {2} ({3})",
                    DateTime.Now.ToString(), change, e.NetworkInterface.InterfaceName,
                    e.NetworkInterface.InterfaceType.ToString());

        // We are making UI updates, so make sure these happen on the UI thread.
        Dispatcher.BeginInvoke(() =>
        {
            Changes.Add(changeInformation); //Changes contains the changeInformation
        });
目前的结果是


但这种格式一点也不好,有时会变得混乱。我希望能够格式化它,使
DateTime.Now.ToString()
位于顶行,然后
change
位于下一行,然后是
e.NetworkInterface.InterfaceName
e.NetworkInterface.InterfaceType.ToString()
。我怎样才能做到这一点呢?

使用显式
\r\n
或者更好的是使用
环境

String.Format(" {0}{1}{2}{3}{4}({5})",
                DateTime.Now, Environment.NewLine, 
                change, Environment.NewLine, 
                e.NetworkInterface.InterfaceName,
                e.NetworkInterface.InterfaceType);

另外请注意,参数中不需要裸的
.ToString()
,这在
String.Format()
中有暗示,我认为您必须添加新行

string changeInformation = String.Format(" {0} {1} {2} {3} ({4})",
                    DateTime.Now.ToString(), Environment.NewLine, change, e.NetworkInterface.InterfaceName,
                    e.NetworkInterface.InterfaceType.ToString());
使用换行符。。。(\n help)
String.Format(“{0}\n{1}\n{2}({3})”,…