I want to create an instance of IEnumerable<T>
- I can do that by creating a method like
public IEnumerator<T> MakeEnumerator(){
yield return 1;
}
But I need to pass this Enumerator to another class and so wanted to see whether I could create this inline with a delegate
Is that possible
EDIT: What I would like to remove is something like this:
new CustomClass(MakeEnumerator())
and replace with
new CustomClass(delegate... ) // The method is now inl开发者_开发知识库ine
An iterator method cannot be made inline, for the simple reason that the code magic that is involved with anonymous methods doesn't support the code magic that is involved when creating iterator methods, or vice versa. An iterator method must be a separate methods, at least in current versions of C#.
However, if all you need is something that can be enumerated over, you can simply use an array.
So, to call method Test, with an enumerable collection:
Test(new[] { 1 });
If you need an IEnumerator<T>
and not an IEnumerable<T>
, simply call GetEnumerator
before passing it to the method:
Test(new[] { 1 }.GetEnumerator());
Delegates can not implement interfaces, so they can not be passed instead of IEnumerator interface. Only you can do is pass return value of delegate - i.e.:
var fuu = new CustomClass(Enumerable.Range( 1, 1 ))
.
精彩评论