首页 > 解决方案 > 为什么在 WinForm 的 TextBox 中结合调用 AppendLine 和 StringBuilder 的 Length 会产生奇怪的结果?

问题描述

我正在练习windows窗体。

这本书最近教过StringBuilder,所以我输入了书中的例子。

示例代码是

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp32
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            StringBuilder str1;
            str1 = new StringBuilder(5);
            str1.Append("1234");
            textBox1.AppendText("Capacity=" + str1.Capacity.ToString() + "\r\n");
            str1.Append("5768");
            textBox1.AppendText("str1=" + str1.ToString() + "\r\n");
            textBox1.AppendText("Length=" + str1.Length.ToString() + "\r\n");

            str1.Length = 15;
            textBox1.AppendText("Capacity=" + str1.Capacity.ToString() + "\r\n");
            textBox1.AppendText("Length=" + str1.Length.ToString() + "\r\n");
            textBox1.AppendText("str1=" + str1.ToString() + "\r\n");

            str1.Clear();
            str1.Append("123");
            textBox1.AppendText("str1=" + str1.ToString() + "\r\n");

        }

       
    }
}

当它显示在 FormsApp 上时,它看起来像这样:

在此处输入图像描述

str1=123没有上新线,

所以我"\r\n"在前面加了"str1=" + str1.ToString() + "\r\n"

之后,FormsApp 显示如下:

在此处输入图像描述

我的问题是:

我已经"\r\n"在以前的AppendText.

使用 Clear() 和 Append() 方法后,

为什么str1=123不自动换行?

..................................................... .

将 Append() 更改为 AppendLine() 后,

FormsApp 显示如下:

在此处输入图像描述

我只改str1.Append("123");str1.AppendLine("123"+"\r\n"),还是不行。

标签: c#.netwinformsnewlinestringbuilder

解决方案


我怀疑大多数评论者都没有详细阅读代码,因此没有意识到您对文本框的所有附加都已经包含换行符。

那么 - 为什么他们不显示?

您遇到了Null 字符的变体,删除了 TextBox 和 RichTextBox 中的其余输出。基本上,如果您将文本插入文本框,那么NULL字符之后的任何内容都会被剥离。

但是这个NULL角色是从哪里来的呢?

好吧,它来自StringBuilder(当您明确地将 设置Length为大于当前长度时)。根据文档

如果指定长度小于当前长度,则将当前 StringBuilder 对象截断为指定长度。如果指定的长度大于当前长度,则在当前 StringBuilder 对象的字符串值的末尾用 Unicode NULL 字符 (U+0000) 填充。

现在,由于您在字符之后插入了换行符,因此NULL在您第二次调用时有效地丢失了换行符

textBox1.AppendText("str1=" + str1.ToString() + "\r\n");

最简单的解决方案是注释掉:

str1.Length = 15;

以避免NULL角色首先到达那里。


推荐阅读