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


C# CharEnumerator.Dispose()用法及代码示例


此方法用于释放CharEnumerator类的当前实例使用的所有资源。 Dispose()方法使CharEnumerator处于不可用状态。因此,当用户完成使用CharEnumerator的工作时,应调用此方法。

用法:

public void Dispose ();

返回值:此方法不返回任何内容。


以下示例程序旨在说明CharEnumerator.Dispose()方法的使用:

示例1:

// C# program to illustrate the 
// use of CharEnumerator.Dispose() 
// Method 
using System; 
  
class GFG { 
  
    // Driver code 
    public static void Main() 
    { 
        // Initialize a string object 
        string str = "GeeksforGeeks is Awesome!"; 
  
        // Instantiate a CharEnumerator object 
        CharEnumerator chEnum = str.GetEnumerator(); 
  
        // Print the string using CharEnumerator 
        while (chEnum.MoveNext()) 
            Console.Write(chEnum.Current); 
  
        // CharEnumerator object is disposed 
        chEnum.Dispose(); 
  
        // Try printing current character 
        // using CharEnumerator 
        try
        { 
  
            Console.Write(chEnum.Current); 
        } 
  
        catch (Exception e)  
        { 
            Console.Write("\nShows " + e.GetType() + " as"+ 
                 " the CharEnumerator object is disposed."); 
        } 
    } 
}
输出:
GeeksforGeeks is Awesome!
Shows System.NullReferenceException as the CharEnumerator object is disposed.

示例2:

// C# program to illustrate the 
// use of CharEnumerator.Dispose() 
// Method 
using System; 
  
class GFG { 
  
    // Driver code 
    public static void Main() 
    { 
        // Initialize a string object 
        string str = "GeeksforGeeks is Awesome"; 
  
        // Instantiate a CharEnumerator object 
        CharEnumerator chEnum = str.GetEnumerator(); 
  
        while (chEnum.MoveNext())  
        { 
            // Print current character 
            Console.Write(chEnum.Current); 
  
            // Dispose the CharEnumerator object 
            // when space is encountered 
            if (chEnum.Current == ' ') 
            { 
                Console.WriteLine(".\nDispose CharEnumerator object and "+ 
                                        "try to print current character."); 
                chEnum.Dispose(); 
                break; 
            } 
        } 
   
        // Try printing current character 
        // using CharEnumerator 
        try
        { 
            Console.Write(chEnum.Current); 
        } 
          
        catch (Exception e)  
        { 
            Console.Write("Shows " + e.GetType() + " as the"+ 
                      " CharEnumerator object is disposed."); 
        } 
    } 
}
输出:
GeeksforGeeks .
Dispose CharEnumerator object and try to print current character.
Shows System.NullReferenceException as the CharEnumerator object is disposed.

参考:



相关用法


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