StringBuilder 和容量? [英] StringBuilder and capacity?

查看:32
本文介绍了StringBuilder 和容量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了测试应用程序来测试,StringBuilder 是否将数据复制到另一个实例并在其长度超过当前容量时增加缓冲区并在 ildasm.exe 中验证,但它似乎相同.

I have created test application to test, Is StringBuilder copy data to another instance and grow it buffer when its length is more than current capacity and verify in ildasm.exe but it seem identical.

如何验证 StringBuilder 将其数据复制到新实例中并按指定的限制增长缓冲区?

How to verify StringBuilder will copy its data into new instance and grow the buffer by the specified limit?

推荐答案

如果您想检查 StringBuilder 的实现方式,只需启动 Reflector 并查看它.StringBuilder.Append(string) 的实现如下

If you want to inspect how StringBuilder is implemented, just fire up Reflector and look at it. The implementation for StringBuilder.Append(string) is as follows

public StringBuilder Append(string value)
{
   if (value != null)
   {
      string stringValue = this.m_StringValue;
      IntPtr currentThread = Thread.InternalGetCurrentThread();
      if (this.m_currentThread != currentThread)
      {
         stringValue = string.GetStringForStringBuilder(stringValue, stringValue.Capacity);
      }
      int length = stringValue.Length;
      int requiredLength = length + value.Length;
      if (this.NeedsAllocation(stringValue, requiredLength))
      {
         string newString = this.GetNewString(stringValue, requiredLength);
         newString.AppendInPlace(value, length);
         this.ReplaceString(currentThread, newString);
      }
      else
      {
         stringValue.AppendInPlace(value, length);
         this.ReplaceString(currentThread, stringValue);
      }
   }
   return this;
}

查看包含 NeedsAllocationGetNewString 等的部分以找到您要查找的内容.

Look at the section with NeedsAllocation, GetNewString and so forth to find what you're looking for.

这篇关于StringBuilder 和容量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆