c# - 字符串生成器 : Can StringBuilder's length & capacity exceed its MaxCapacity

标签 c# .net string stringbuilder

StringBuilder追加字符串时,Capacity和Length是否可以超过MaxCapacity

根据 MSDN MaxCapacity 定义为“字符串生成器实例可以容纳的最大字符数”。但是这种行为在下面的两个代码片段中是不一致的:

片段 1: 在下面的代码中,当 StringBuilder 的长度超过其 MaxCapacity 时将抛出 ArgumentOutOfRangeException - 这是预期的。

        String str = sb.ToString();

        StringBuilder sb1 = new StringBuilder(3, 5);
        sb1.Append("1");      //no error as Length 1 <= max limit 5         
        sb1.Append("12");     //no error as Length 3 <= max limit 5           
        sb1.Append("123");    //ArgumentOutOfRangeException Thrown as Length 6 > max limit 5

片段 2: 在下面的代码中,当 StringBuilder 的长度超过其 MaxCapacity 时,不会抛出 ArgumentOutOfRangeException - 这种行为似乎是不正确的。

        StringBuilder sb = new StringBuilder(3, 5);

        sb.Append("1"); //no error as Length 1 <= max limit 5         
        sb.Append("2"); //no error as Length 2 <= max limit 5         
        sb.Append("3"); //no error as Length 3 <= max limit 5         
        sb.Append("4"); //no error as Length 4 <= max limit 5         
        sb.Append("5"); //no error as Length 5 <= max limit 5         
        sb.Append("6"); //Even though Length 6 > max limit 5 NO EXCEPTION IS THROWN         

        String str = sb.ToString(); //Contains "123456"

任何人都可以解释这两种情况下发生的情况以及行为差异的原因吗?

最佳答案

StringBuilder Constructor (Int32, Int32)

Notes to Callers
In the .NET Framework 4 and the .NET Framework 4.5, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. This can occur particularly when you call the Append and AppendFormat methods to append small strings.

其他资源:

结论:

出于性能原因,此类以这种方式编写,如官方文档所述,它的 CapacityLength 可以超出其 MaxCapacity特别是在附加小字符串时。此外,如文档中所述,一些默认值是特定于实现的,因此您最好不要依赖CapacityMaxCapacity,并且仅出于性能原因在这些条件下使用此类:

  • 当您希望您的应用在设计时对字符串进行未知数量的更改时(例如,当您使用循环连接随机数量的包含用户输入的字符串时)。
  • 当您希望您的应用对字符串进行大量更改时。

关于c# - 字符串生成器 : Can StringBuilder's length & capacity exceed its MaxCapacity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32432497/

相关文章:

c# - 使用 Aforge.net 或 C# 获取或设置相机属性(例如曝光时间)

java - 我们可以使用 Java selenium 代码进行 .net Web 应用程序测试吗?

c# - 在内存中缓存数据库表

javascript - 如何从字符串中的方法名称调用 javascript 函数?

python - 用 Python 实现文本编辑器

c# - 在GridView/DetailsView中显示外键数据

c# - 如何在不派生抽象类的情况下直接调用抽象类的非抽象方法?

c# - 委托(delegate)中的协方差,有什么例子吗?

sql - 将字符串拆分成行Oracle SQL

c# - 通过linq中的where子句选择全部