问题
I'm newb with generics/iterators/enumerators etc.
I have code, it keeps field number (int) and error mesages (List string) for each field:
public class ErrorList : IEnumerable // ?
{
private Dictionary <int, List<string>> errorList;
// ...
}
How to make this class work with foreach loop? I wanna use GetEnumerator form Dictionary, but how should i do this?
回答1:
You could simply provide a public GetEnumerator
method:
public class ErrorList
{
private Dictionary<int, List<string>> errorList = new Dictionary<int, List<string>>();
... some methods that fill the errorList field
public IEnumerator<KeyValuePair<int, List<string>>> GetEnumerator()
{
return errorList.GetEnumerator();
}
}
and now assuming you have an instance of ErrorList:
var errors = new ErrorList();
you can loop through them:
foreach (KeyValuePair<int, List<string>> item in errors)
{
...
}
回答2:
Dictionary implements IEnumerable<KeyValuePair<TKey, TValue>>
, so this works:
foreach (KeyValuePair<Int, List<String>> kvp in errorList) {
var idx = kvp.Key;
var vals = kvp.Value;
// ... do whatever here
}
回答3:
You can simply return errorList.GetEnumerator()
.
来源:https://stackoverflow.com/questions/9844159/ienumerable-implementing-using-getenumerator-from-local-variable