StringBuilder.EnsureCapacity() 方法


C# 中的 StringBuilder.EnsureCapacity() 方法用于确保以此 StringBuilder 为实例的容量至少为指定的值。

语法

语法如下 −

public int EnsureCapacity (int capacity);

上面,参数 capacity 是要确保的最小容量。

示例

我们现在来看一个示例 −

 实际演示

using System;
using System.Text;
public class Demo{
   public static void Main(){
      StringBuilder strBuilder = new StringBuilder("jhbjhb");
      Console.WriteLine("String = "+strBuilder);
      Console.WriteLine("StringBuilder capacity= "+strBuilder.Capacity);
      strBuilder.EnsureCapacity(20);
      Console.WriteLine("StringBuilder capacity= "+strBuilder.Capacity);
      char[] arr = new char[5] {'a', 'b', 'c', 'd', 'e'};
      strBuilder.CopyTo(1, arr, 1, 3);
      Console.WriteLine("
Copied String in char array...");       Console.WriteLine(arr);    } }

输出

它会生成以下输出 −

String = jhbjhb
StringBuilder capacity= 16
StringBuilder capacity= 20
Copied String in char array...
ahbje

示例

我们现在再来看另一个示例 −

 实际演示

using System;
using System.Text;
public class Demo{
   public static void Main(){
      StringBuilder strBuilder = new StringBuilder("Katie");
      Console.WriteLine("String = "+strBuilder);
      Console.WriteLine("
StringBuilder capacity = "+strBuilder.Capacity);       Console.WriteLine("StringBuilder length = "+strBuilder.Length);       strBuilder.EnsureCapacity(35);       Console.WriteLine("
StringBuilder capacity= "+strBuilder.Capacity);       Console.WriteLine("StringBuilder length = "+strBuilder.Length);       strBuilder.EnsureCapacity(0);       strBuilder.Length = 0;       Console.WriteLine("
StringBuilder capacity= "+strBuilder.Capacity);       Console.WriteLine("StringBuilder length = "+strBuilder.Length);    } }

输出

它会生成以下输出 −

String = Katie
StringBuilder capacity = 16
StringBuilder length = 5
StringBuilder capacity= 35
StringBuilder length = 5
StringBuilder capacity= 35
StringBuilder length = 0

更新日期: 03-12-2019

90 次浏览

开启您的职业生涯

完成课程以获得认证

立即开始
广告