간단한 IEnumerator 사용 (예제 포함)
IEnumerator
C #에서 s 를 사용하는 방법 (이유는 아님)을 기억하는 데 문제가 있습니다 . 나는 초보자에게 모든 것을 아주 잘 설명하는 훌륭한 문서로 Java에 익숙합니다. 그러니 제발 참아주세요.
나는이 보드의 다른 답변에서 배우려고 시도했지만 소용이 없었습니다. 이전에 이미 물어 보았던 일반적인 질문을하는 대신, 나를 위해 명확하게 해줄 구체적인 예가 있습니다.
IEnumerable<String>
객체를 전달해야하는 메서드가 있다고 가정 합니다. 메서드 는 반복기 roxxors
의 모든 끝에 문자 를 연결 String
하기 만하면됩니다. 그런 다음이 새 반복자를 반환합니다 (물론 원래 IEnumerable
객체는 그대로 남아 있습니다).
어떻게해야합니까? 여기에 대한 대답은 물론 저뿐만 아니라 이러한 개체에 대한 기본적인 질문에 많은 도움이 될 것입니다.
다음은에 대한 문서입니다 IEnumerator
. 목록의 값을 가져 오는 데 사용되며 길이가 반드시 미리 알려지지는 않습니다. 이 단어는 enumerate
"하나 하나 세거나 이름을 짓다"를 의미하는 에서 유래했습니다 .
IEnumerator
및 IEnumerator<T>
모두에 의해 제공되는 IEnumerable
그리고 IEnumerable<T>
통해 .NET에서 (후자가 모두 제공) 인터페이스 GetEnumerator()
. 이는 foreach
문이 이러한 인터페이스 메서드를 통해 열거 자와 직접 작동하도록 설계 되었기 때문에 중요 합니다.
예를 들면 다음과 같습니다.
IEnumerator enumerator = enumerable.GetEnumerator();
while (enumerator.MoveNext())
{
object item = enumerator.Current;
// Perform logic on the item
}
된다 :
foreach(object item in enumerable)
{
// Perform logic on the item
}
특정 시나리오와 관련하여 .NET의 거의 모든 컬렉션은 IEnumerable
. 따라서 다음을 수행 할 수 있습니다.
public IEnumerator Enumerate(IEnumerable enumerable)
{
// List implements IEnumerable, but could be any collection.
List<string> list = new List<string>();
foreach(string value in enumerable)
{
list.Add(value + "roxxors");
}
return list.GetEnumerator();
}
public IEnumerable<string> Appender(IEnumerable<string> strings)
{
List<string> myList = new List<string>();
foreach(string str in strings)
{
myList.Add(str + "roxxors");
}
return myList;
}
또는
public IEnumerable<string> Appender(IEnumerable<string> strings)
{
foreach(string str in strings)
{
yield return str + "roxxors";
}
}
using the yield construct, or simply
var newCollection = strings.Select(str => str + "roxxors"); //(*)
or
var newCollection = from str in strings select str + "roxxors"; //(**)
where the two latter use LINQ and (**)
is just syntactic sugar for (*)
.
If i understand you correctly then in c# the yield return
compiler magic is all you need i think.
e.g.
IEnumerable<string> myMethod(IEnumerable<string> sequence)
{
foreach(string item in sequence)
{
yield return item + "roxxors";
}
}
I'd do something like:
private IEnumerable<string> DoWork(IEnumerable<string> data)
{
List<string> newData = new List<string>();
foreach(string item in data)
{
newData.Add(item + "roxxors");
}
return newData;
}
Simple stuff :)
Also you can use LINQ's Select Method:
var source = new[] { "Line 1", "Line 2" };
var result = source.Select(s => s + " roxxors");
Read more here Enumerable.Select Method
참고URL : https://stackoverflow.com/questions/7310454/simple-ienumerator-use-with-example
'development' 카테고리의 다른 글
URL에서 파일 다운로드 / 스트리밍-asp.net (0) | 2020.11.14 |
---|---|
Capybara에서 자바 스크립트 팝업을 어떻게 확인합니까? (0) | 2020.11.14 |
Android에서 Bitmap과 Drawable의 차이점은 무엇입니까? (0) | 2020.11.14 |
자바 : 정적 초기화 블록은 언제 유용합니까? (0) | 2020.11.14 |
쿠키 도메인의 점 접두사는 무엇을 의미합니까? (0) | 2020.11.14 |