当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C# StringBuilder.EnsureCapacity()用法及代码示例


StringBuilder类的GuaranteeCapacity(Int32)方法可帮助我们确保容量至少等于作为参数传递给该方法的指定值。如果当前容量小于Capacity参数,则重新分配该实例的内存以容纳至少容量个字符;否则,不会更改任何内存。

用法: public int EnsureCapacity (int capacity);
Here, the capacity is the minimum capacity to ensure.

返回值:它返回当前实例的新容量。


异常:如果容量小于零,或者此实例的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

参考:



相关用法


注:本文由纯净天空筛选整理自Kirti_Mangal大神的英文原创作品 StringBuilder.EnsureCapacity() Method in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。