當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。