StringBuilder类的GuaranteeCapacity(Int32)方法可帮助我们确保容量至少等于作为参数传递给该方法的指定值。如果当前容量小于Capacity参数,则重新分配该实例的内存以容纳至少容量个字符;否则,不会更改任何内存。
Syntax: public int EnsureCapacity (int capacity);
Here, the capacity is the minimum capacity to ensure.
Return Value: It returns the new capacity of the current instance.
异常:如果容量小于零,或者此实例的Enlarging值超过MaxCapacity,则此方法将提供ArgumentOutOfRangeException 。
范例1:
// C# program to demonstrate
// the EnsureCapacity Method
using System;
using System.Text;
class GFG {
// Main Method
public static void Main(String[] args)
{
// create a StringBuilder object
StringBuilder str = new StringBuilder();
// print string capacity
Console.WriteLine("Before EnsureCapacity "
+ "method capacity = "
+ str.Capacity);
// apply ensureCapacity()
str.EnsureCapacity(18);
// print string capacity
Console.WriteLine("After EnsureCapacity"
+ " method capacity = "
+ str.Capacity);
}
}
输出:
Before EnsureCapacity method capacity = 16
After EnsureCapacity method capacity = 18
范例2:
// C# program to demonstrate
// the EnsureCapacity Method
using System;
using System.Text;
class GFG {
// Main Method
public static void Main(String[] args)
{
// create a StringBuilder object
StringBuilder str = new StringBuilder();
// print string capacity
Console.WriteLine("Before EnsureCapacity "
+ "method capacity = "
+ str.Capacity);
// apply ensureCapacity()
str.EnsureCapacity(44);
// print string capacity
Console.WriteLine("After EnsureCapacity"
+ " method capacity = "
+ str.Capacity);
}
}
输出:
Before EnsureCapacity method capacity = 16
After EnsureCapacity method capacity = 44
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.text.stringbuilder.ensurecapacity?view=netframework-4.7.2