开发者

Moving A Method Inline - Resharper Possible

开发者 https://www.devze.com 2023-03-03 22:22 出处:网络
I want to create an instance of IEnumerable<T> - I can do that by creating a method like public IEnumerator<T> MakeEnumerator(){

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 ))

.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号