c# - 为什么在 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")
,还是不行。
解决方案
我怀疑大多数评论者都没有详细阅读代码,因此没有意识到您对文本框的所有附加都已经包含换行符。
那么 - 为什么他们不显示?
您遇到了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
角色首先到达那里。
推荐阅读
- javascript - 如果另一个 API 没有数据,则仅使用一个 API
- r - 使用 R 将矩阵保存到文件中
- console - Pitest:如何将日志输出重定向到文件?
- git - 将用户名全局更改为 git 后设置相同的用户
- javascript - 在 else 块内有一个 if - else 块是最佳做法吗
- javascript - Angular 6 cookie 过期或 Angular 6 中的更改事件
- reactjs - 如何访问从 props 返回的数据
- java - 是否存在具有队列限制的 ExecutorService 实现以及用新队列成员替换旧队列成员的选项?
- python - pandas str.contains() 给出错误的结果?
- apache - 隐藏目录内容并禁用除特定目录之外的所有目录的目录浏览