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.
参考:
- https://docs.microsoft.com/en-us/dotnet/api/system.charenumerator.dispose?view=netframework-4.7.2