CharEnumerator.Current 属性

定义

获取由此 CharEnumerator 对象枚举的字符串中当前引用的字符。

public char Current { get; }

属性值

当前由此 CharEnumerator 对象引用的 Unicode 字符。

实现

例外

该索引无效;即它位于枚举字符串的第一个字符之前或最后一个字符之后。

示例

以下示例使用 CharEnumerator 类枚举字符串中的单个字符。 它通过调用 String.GetEnumerator 方法实例化CharEnumerator对象,通过调用 MoveNext 方法从一个字符移动到下一个字符,并通过检索 属性的值Current显示当前字符。

string title = "A Tale of Two Cities";
CharEnumerator chEnum = title.GetEnumerator();
int ctr = 1;
string outputLine1 = null;
string outputLine2 = null;
string outputLine3 = null;

while (chEnum.MoveNext())
{
   outputLine1 += ctr < 10 || ctr % 10 != 0 ? "  " : (ctr / 10) + " ";
   outputLine2 += (ctr % 10) + " ";
   outputLine3 += chEnum.Current + " ";
   ctr++;
}

Console.WriteLine("The length of the string is {0} characters:",
                  title.Length);
Console.WriteLine(outputLine1);
Console.WriteLine(outputLine2);
Console.WriteLine(outputLine3);
// The example displays the following output to the console:
//       The length of the string is 20 characters:
//                         1                   2
//       1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
//       A   T a l e   o f   T w o   C i t i e s

但请注意,通过使用 foreach C#) 中的 (或 For Each Visual Basic) 中的 (,可以更直观地执行相同的操作,如以下示例所示。

string title = "A Tale of Two Cities";
int ctr = 1;
string outputLine1 = null;
string outputLine2 = null;
string outputLine3 = null;

foreach (char ch in title)
{
   outputLine1 += ctr < 10 || ctr % 10 != 0 ? "  " : (ctr / 10) + " ";
   outputLine2 += (ctr % 10) + " ";
   outputLine3 += ch + " ";
   ctr++;
}

Console.WriteLine("The length of the string is {0} characters:",
                  title.Length);
Console.WriteLine(outputLine1);
Console.WriteLine(outputLine2);
Console.WriteLine(outputLine3);
// The example displays the following output to the console:
//       The length of the string is 20 characters:
//                         1                   2
//       1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
//       A   T a l e   o f   T w o   C i t i e s

注解

CharEnumerator 维护枚举字符串的内部索引,属性 Current 返回索引当前引用的字符。 仅当索引有效时,才应调用此属性;否则,将引发异常。

对于空字符串 (“”) ,索引始终无效。 调用 或 Reset 方法后,String.GetEnumerator索引也无效。 调用上述任一方法后,调用 MoveNext 方法将索引调整为枚举字符串中的第一个字符。 每当方法返回 true时,MoveNext索引都有效。

Current 不会移动索引,并且连续调用 以 Current 返回相同的字符,直到 MoveNext调用 、 ResetString.GetEnumerator

适用于

产品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1