Visual Studio和string.format中的新行参数问题

时间:2013-09-10 09:07:57

标签: c# .net visual-studio visual-studio-2012

我覆盖了我的ToString()方法,我的类包含许多字段 我只能在最后一个字符串后面添加新行,并且只将变量放在下一行中 注意 - 这只是出于视觉目的,我不希望在打印之间分开一行。只是为了看到我的21“屏幕中的整行而不滚动。

这有效:

    public override string ToString()
    {
        return String.Format("{0}, IsAccessible = {1}, NetworkAddress = {2}, Manufacturer = {3}, Model = {4}, Firmware = {5}, Driver = {6}, MacAddress = {7}, Scenes count = {8}",
            base.ToString(), IsAccessible, NetworkAddress, Manufacturer, Model, Firmware, Driver, MacAddress, Scenes.Count);
    }

但这确实无效(相同的代码,仅在第4次参数后按下输入):

    public override string ToString()
    {
        return String.Format("{0}, IsAccessible = {1}, NetworkAddress = {2}, Manufacturer = {3}, Model = {4},
        Firmware = {5}, Driver = {6}, MacAddress = {7}, Scenes count = {8}",
            base.ToString(), IsAccessible, NetworkAddress, Manufacturer, Model, Firmware, Driver, MacAddress, Scenes.Count);
    }

4 个答案:

答案 0 :(得分:2)

String是引号之间一行中的符号序列。

"one two" - is string.
"one
  two" - is an error.

您可以通过串联有效字符串在c#中创建多行字符串:

String s = "one" + Environment.NewLine + 
           " two";

或在字符串

之前添加@
String s = @"one
             two";

答案 1 :(得分:1)

使用逐字字符串,以@字符开头的字符串:

public override string ToString()
{
    return String.Format(@"{0}, IsAccessible = {1}, NetworkAddress = {2}, Manufacturer = {3}, Model = {4},
    Firmware = {5}, Driver = {6}, MacAddress = {7}, Scenes count = {8}",
        base.ToString(), IsAccessible, NetworkAddress, Manufacturer, Model, Firmware, Driver, MacAddress, Scenes.Count);
}

答案 2 :(得分:0)

我能想到的唯一一件事如下:

public override string ToString()
{
    return String.Format(
        "{0}, IsAccessible = {1}, NetworkAddress = {2}, Manufacturer = {3},"
        + " Model = {4}, Firmware = {5}, Driver = {6}, MacAddress = {7},"
        + " Scenes count = {8}",
        base.ToString(), IsAccessible, NetworkAddress, Manufacturer, Model, Firmware, Driver, MacAddress, Scenes.Count);
}

答案 3 :(得分:0)

试试这个:

string temp_var = @"{0}, IsAccessible = {1}, NetworkAddress = {2}, Manufacturer = {3}, Model = {4},
          Firmware = {5}, Driver = {6}, MacAddress = {7}, Scenes count = {8}";
temp_var = string.Format(base.ToString(), IsAccessible, NetworkAddress, Manufacturer, Model, Firmware, Driver, MacAddress, Scenes.Count);
return temp_var;

只需将值赋给字符串变量..