Please guide me in getting the following line c# lambda expression code
<%= MyClass.GetData(() => new[] { Html.TextBox(prefix + "Postcode", Customer.ZipCode, new { maxlength = 7 }), Html.ValidationIcon(prefix + "ZipCode") })%>
Can so开发者_开发技巧meone please explain me what the MyClass.GetData method is getting passed as parameter?
I don't expect a full explanation and i know that i should learn further into anonyous methods and lamda expression... But for now can you explain what the the code as from "() =>......." means?
And if you know some nice articles that builds towards understanding material like this that would be cool !
The () => new [] { ... } is a lambda expression which is short-hand syntax for an anonymous delegate. This means that you are passing in essentially the equivalent of a pointer to a function that takes no arguments, the () part indicates the arguments, and returns the results in { } braces (Html.TextBox.... etc).
Essentially, this would be equivalent to passing a method name that accomplishes the same thing, but it's more concise syntax:
MyClass.GetData(() => new[] { Html.TextBox(prefix + "Postcode", Customer.ZipCode, new { maxlength = 7 }), Html.ValidationIcon(prefix + "ZipCode") }
is the same, roughly, as creating a method, then passing that method name in.
private WebControl[] GetControls()
{
return new[] { Html.TextBox(prefix + "Postcode", Customer.ZipCode, new { maxlength = 7 }), Html.ValidationIcon(prefix + "ZipCode");
}
....
MyClass.GetData(GetControls);
p.s. Here's a good basic lambda tutorial: http://blogs.msdn.com/b/ericwhite/archive/2006/10/03/lambda-expressions.aspx
() =>
means an lambda that does not take any parameters. So you are passing into GetData
a lambda that takes no parameters and returns a new array.
It means: Here is an anonymous delegate that takes no argument and returns an array of objects whose type will be inferred from the return values of Html.TextBox()
and Html.ValidationIcon()
.
精彩评论