영어로 읽기

다음을 통해 공유


CharEnumerator.Current 속성

정의

CharEnumerator 개체에서 열거한 문자열의 현재 참조되는 문자를 가져옵니다.

public char Current { get; }

속성 값

CharEnumerator 개체에서 현재 참조하는 유니코드 문자입니다.

구현

예외

인덱스가 유효하지 않는 경우. 즉, 인덱스가 열거형 문자열의 첫 번째 문자 앞이나 마지막 문자 뒤의 위치입니다.

예제

다음 예제에서는 클래스를 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

그러나 다음 예제와 같이 (C#) 또는 For Each (Visual Basic의 경우)를 사용하여 foreach 동일한 작업을 다소 직관적으로 수행할 수 있습니다.

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 에 대한 내부 인덱스를 유지하고 속성은 현재 인덱스에서 참조하는 문자를 반환합니다. 인덱스가 유효한 경우에만 이 속성을 호출해야 합니다. 그렇지 않으면 예외가 throw됩니다.

빈 문자열("")의 인덱스는 항상 유효하지 않습니다. 또는 Reset 메서드가 호출된 후에도 인덱스가 String.GetEnumerator 잘못되었습니다. 이러한 메서드 중 하나가 호출된 후 메서드를 MoveNext 호출하여 인덱스가 열거된 문자열의 첫 번째 문자로 조정됩니다. 인덱스는 메서드가 를 반환할 MoveNext 때마다 유효합니다 true.

Current는 인덱스 및 연속 호출을 Current 이동하지 않고 , Reset또는 String.GetEnumerator 가 호출될 때까지 MoveNext동일한 문자를 반환합니다.

적용 대상

제품 버전
.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