StringBuilder.Capacity属性用于获取或设置当前实例分配的内存中可以包含的最大字符数。
Syntax: public int Capacity { get; set; }
Return Value: This property will return the maximum number of characters that can be contained in the memory allocated by the current instance. Its value can range from Length to MaxCapacity.
Exception: This property will give ArgumentOutOfRangeException if the value specified for a set operation is less than the current length of this instance or the value specified for a set operation is greater than the maximum capacity.
下面的程序将说明上述属性的用法:
范例1:
// C# program to demonstrate
// the Capacity() Property
using System;
using System.Text;
class GFG {
// Main Method
public static void Main(String[] args)
{
// create a StringBuilder object,
// default capacity will be 16
StringBuilder str = new StringBuilder();
// get default capacity
int cap = str.Capacity;
Console.WriteLine("Deafult Capacity of StringBuilder = "
+ cap);
// add the String to StringBuilder Object
str.Append("Geek");
// get capacity
cap = str.Capacity;
// print the result
Console.WriteLine("StringBuilder = " + str);
Console.WriteLine("Current Capacity of StringBuilder = "
+ cap);
}
}
输出:
Deafult Capacity of StringBuilder = 16
StringBuilder = Geek
Current Capacity of StringBuilder = 16
范例2:
// C# program to demonstrate
// the Capacity() Property
using System;
using System.Text;
class GFG {
public static void Main(String[] args)
{
// create a StringBuilder object
// with a String passed as parameter
StringBuilder str =
new StringBuilder("WelcomeGeeks");
// get capacity
int capacity = str.Capacity;
// print the result
Console.WriteLine("StringBuilder = " + str);
Console.WriteLine("Capacity of StringBuilder = "
+ capacity);
}
}
输出:
StringBuilder = WelcomeGeeks
Capacity of StringBuilder = 16
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.text.stringbuilder.capacity?view=netframework-4.7.2