Why is this delegate syntax "legal"?
I am reading about anonymous methods and am trying to wrap my head around this example:
Li开发者_开发百科st<int> evenNumbers = list.FindAll(delegate(int i)
{ return (i % 2) == 0; } )
Why is delegate(int i)
legal? You aren't having to declare new delegate void
or anything like that.
Is that what is meant by anonymous method? Is this the added syntactic sugar that allows for anonymous methods?
It's legal because of what you suspect, it's creating an anonymous delegate/method.
An alternative (using the lambda operator =>) would be:
List<int> evenNumbers = list.FindAll((i) => ((i % 2) == 0));
or
List<int> evenNumbers = list.FindAll(i => i % 2 == 0);
See Lambda Expressions for further reading.
If you decompose the statement a little, hopefully it will be more obvious - this is the equivalent code.
Predicate<int> test = delegate(int i)
{
return (i % 2) == 0;
};
List<int> evenNumbers = list.FindAll(test);
As you can see it created an anonymous delegate (that the compiler will turn into a method behind the scenes)
Personally I've always found the "inline" anonymous delegate syntax to cloud the issue more than add clarity whereas the same construct built using a lambda expression, once you are used to the syntax, adds clarity
List<int> evenNumbers = list.FindAll(i => i % 2 == 0);
in this code it seems like passing a method into a method using a delegate.
精彩评论