StringBuilder(Int32)构造函数用于初始化StringBuilder类的新实例,该实例将为空并具有指定的初始容量。 StringBuilder的用于表示字符的可变的字符串。可变是指可以更改的字符串。所以String对象是不可变的,但StringBuilder是可变的字符串类型。它不会创建当前字符串对象的新修改实例,但会在现有字符串对象中进行修改。
句法:
public StringBuilder (int capacity);
在这里,容量是StringBuilder实例的起始大小。如果要存储的字符数大于指定的容量,则StringBuilder对象将动态分配内存以存储它们。
异常:如果容量小于零,则将提供ArgumentOutOfRangeException。
范例1:
// C# Program to illustrate how
// to create a StringBuilder having
// specified initial capacity
using System;
using System.Text;
using System.Collections;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// sb is the StringBuilder object
// StringBuilder(10) is the constructor
// used to initializes a new
// instance of the StringBuilder class
// having 10 as capacity
StringBuilder sb = new StringBuilder(10);
Console.Write("Capacity of StringBuilder: ");
// using capacity property
Console.WriteLine(sb.Capacity);
}
}
输出:
Capacity of StringBuilder: 10
示例2:对于ArgumentOutOfRangeException
// C# Program to illustrate how
// to create a StringBuilder having
// specified initial capacity
using System;
using System.Text;
using System.Collections;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// sb is the StringBuilder object
// taking capacity less than zero
StringBuilder sb = new StringBuilder(-4);
// using capacity property
Console.WriteLine(sb.Capacity);
}
}
运行时错误:
Unhandled Exception:
System.ArgumentOutOfRangeException: ‘capacity’ must be greater than zero.
Parameter name: capacity
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.text.stringbuilder.-ctor?view=netframework-4.7.2#System_Text_StringBuilder__ctor_System_Int32_