StringBuilder 错误 - 未附加字符串
使用长字符串并发现了这个问题。有什么建议吗?
我有一个实例,其中字符串生成器的容量为 1024,长度为 992。
我是 .Append() 一个 .Length 属性为 1024 的字符串。
调用 .Append() 后,.ToString() 方法返回一个 long “\0\0\0”字符串。
到底是怎么回事? 0.o
如果我创建一个新的 StringBuilder 对象然后追加,我会得到我所期望的。那么字符串“应该”没问题吗?
(我通过执行 .Remove(0, LengthofSB) 技巧来清除字符串生成器)。
有什么想法吗?
Working with long strings and found this problem. Any advice?
I have an instance where a string builder's Capacity is 1024 and Length is 992.
I am .Append() a string that has a .Length property of 1024.
After .Append() is called, the .ToString() method returns a long "\0\0\0" string.
What is going on? 0.o
If I create a new StringBuilder object and then append, I get what I expect. So the string "should" be ok right?
(I am clearing the stringbuilder out by doing the .Remove(0, LengthofSB) trick).
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在我看来,
StringBuilder
中的原始数据是“\0\0\0\0\0...”,这就是你所看到的 - 如果你能看到结尾您会看到真实数据的字符串。各种 Windows 控件在看到“\0”时会被截断,因为它们将其视为字符串终止字符,从而加剧了这种情况。
如果你有一个简短但完整的程序来证明这个问题,我们就可以证实我的怀疑。
It sounds to me like the original data in the
StringBuilder
is "\0\0\0\0\0..." and that's what you're seeing - if you could see to the end of the string you'd see your real data.This is exacerbated by various Windows controls truncating when they see "\0" as they treat it as a string termination character.
If you have a short but complete program which demonstrates the problem, we could confirm my suspicion.
我尽可能从我尝试运行下面的代码的问题中看出。如果没有您上面提到的字符串“\0\0\0”,它工作得很好。我已经发布了下面的代码。请注意,因为您没有提供您的表现,我只是认为您正在尝试类似的事情。另外,我只是创建两个 1024 的字符串,其中一个字符串充满“a”和其他“b”,并将它们连接到第一个 stringbuilder 对象中。效果很好。
As much i as i could make out from the question i tried running the following code below. It worked fine without the string "\0\0\0" mentioned by you as above. I have posted the code below. Do note since you have not provided how you were doing, i just think you were trying something like this. Also i am just creating two strings of 1024 with one string full of 'a' and other 'b' and joining them in the first stringbuilder object. it worked fine.
就我而言,我犯了一个菜鸟错误,并创建了一个与 OP 略有不同的问题。它与我附加的字符串无关。我创建了一个带有表达式主体成员的属性。我返回 StringBuilder 的新实例,而不是创建 getter 并使用新实例初始化它,因此每次获得该值时,它都是空的。
也就是说,我有:
而不是期望的:
当我写它时它是有意义的。调试起来很有趣。
寓意:小心你的初始化代码。你得到了你所要求的,但有时却不是你想要的。
In my case, I made a rookie mistake and created a slightly different problem that the OP. It had nothing to do with the strings I was appending. I created a property with an expression-bodied member. I was returning a new instance of StringBuilder instead of creating a getter and initializing it with a new instance, so every time I got the value, it was empty.
That is, I had:
instead of the desired:
It made sense when I wrote it. That was fun to debug.
Moral: be careful with your initialization code. You get what you asked for, but sometimes not what you wanted.