【问题标题】:When I use StringBuilder.Append instead of .AppendLine, do I need to add additional .Append(crlf)s?当我使用 StringBuilder.Append 而不是 .AppendLine 时,是否需要添加额外的 .Append(crlf)s?
【发布时间】:2013-01-22 00:26:37
【问题描述】:

我正在修改我在此处找到的一些代码:http://nicholas.piasecki.name/blog/2009/03/sending-raw-epl2-directly-to-a-zebra-lp2844-via-c/#comment-1636,但在 VS 2003 / .NET 1.1 中,无法识别 StringBuilder 的 AppendLine 方法,因此我将其截断为 .Append。

我现在是否需要在每次调用 Append 后添加 #13#10 左右 - 我假设这是 AppendLine 自动执行的操作。

【问题讨论】:

  • 是的(更多字符,以便我发表评论)
  • 你可以使用 Environment.NewLine

标签: c# .net visual-studio append stringbuilder


【解决方案1】:

是的。

AppendLine() 将附加其参数,然后是 Environment.Newline
如果您不调用AppendLine(),则需要自己添加换行符。

【讨论】:

  • 我想知道对于这个项目(CE/CF)来说,“\r\n”是否比 Environment.Newline(我通常更喜欢)更安全。
  • 它是否附加了\r\n 是否使用Environment.NewLine
  • @ClayShannon:你是对的;我应该说Environment.NewLine
  • Environment.Newline 在 .NET 1.1 中似乎也无法识别
【解决方案2】:

是的。不过,请小心不要将其视为 CRLF - internally StringBuilder uses Environment.Newline,因此值得自己使用 Environment.NewLine 以实现交叉兼容性。

 [System.Runtime.InteropServices.ComVisible(false)]
    public StringBuilder AppendLine() {
        Contract.Ensures(Contract.Result<stringbuilder>() != null);
        return Append(Environment.NewLine);
    }

    [System.Runtime.InteropServices.ComVisible(false)]
    public StringBuilder AppendLine(string value) {
        Contract.Ensures(Contract.Result<stringbuilder>() != null);
        Append(value);
        return Append(Environment.NewLine);
    }

编辑:除非你因为硬件而特别需要使用 CRLF,否则我猜。

【讨论】:

    【解决方案3】:

    StringBuilder.AppendLine 的反编译源

    /// <summary>
    /// Appends the default line terminator to the end of the current <see cref="T:System.Text.StringBuilder"/> object.
    /// 
    /// </summary>
    /// 
    /// <returns>
    /// A reference to this instance after the append operation has completed.
    /// 
    /// </returns>
    /// <exception cref="T:System.ArgumentOutOfRangeException">Enlarging the value of this instance would exceed <see cref="P:System.Text.StringBuilder.MaxCapacity"/>.
    ///                 </exception><filterpriority>1</filterpriority>
    [ComVisible(false)]
    [__DynamicallyInvokable]
    public StringBuilder AppendLine()
    {
      return this.Append(Environment.NewLine);
    }
    

    【讨论】:

    • 感谢您发布此@Dustin Kingen!
    猜你喜欢
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 2018-07-08
    • 1970-01-01
    • 2014-09-24
    • 2021-02-08
    • 2013-11-04
    相关资源
    最近更新 更多