StringBuilder类如何实现?每次我们追加时,它在内部创建新的字符串对象吗?
在.NET 2.0中,它在String内部使用该类。String仅在System名称空间之外是不可变的,因此StringBuilder可以做到这一点。
String
System
StringBuilder
在.NET 4.0中String已更改为使用char[]。
char[]
在2.0中StringBuilder看起来像这样
public sealed class StringBuilder : ISerializable { // Fields private const string CapacityField = "Capacity"; internal const int DefaultCapacity = 0x10; internal IntPtr m_currentThread; internal int m_MaxCapacity; internal volatile string m_StringValue; // HERE ---------------------- private const string MaxCapacityField = "m_MaxCapacity"; private const string StringValueField = "m_StringValue"; private const string ThreadIDField = "m_currentThread";
但是在4.0中,它看起来像这样:
public sealed class StringBuilder : ISerializable { // Fields private const string CapacityField = "Capacity"; internal const int DefaultCapacity = 0x10; internal char[] m_ChunkChars; // HERE -------------------------------- internal int m_ChunkLength; internal int m_ChunkOffset; internal StringBuilder m_ChunkPrevious; internal int m_MaxCapacity; private const string MaxCapacityField = "m_MaxCapacity"; internal const int MaxChunkSize = 0x1f40; private const string StringValueField = "m_StringValue"; private const string ThreadIDField = "m_currentThread";
因此,显然将其从使用a更改string为使用a char[]。
string
编辑:更新了答案以反映.NET 4(我才刚刚发现)中的更改。