c# - Understanding Func<T, TResult> Delegate with MVC -
i trying wrap head around func < t, tresult> delegate seems not clear. know t parameter & tresult return type.
in mvc use function time:
@model products @html.textboxfor(s=>s.my_property)
now how textboxfor function knows parameter passed me "products model".
and below signature textboxfor model:
public static mvchtmlstring textboxfor<tmodel, tproperty>( htmlhelper<tmodel> htmlhelper, expression<func<tmodel, tproperty>> expression, idictionary<string, object> htmlattributes )
so question is, when call html.textboxfor(s), how come method knows "s" "products" model , how tmodel maps parameter "s" (knowing product model , need return something)?
the html
property (@html
) of type htmlhelper<products>
, because of @model products
directive. how razor engine works.
textboxfor
extension method htmlhelper<tmodel>
, , in code, you're calling on instance of htmlhelper<products>
, therefore tmodel
resolved products
.
then, compiler can bind tproperty
type of my_property
there, knows tmodel
, can deduce lambda "returns".
side note: must know expression<func<t>>
totally different func<t>
:
func<...>
simple delegate, reference piece of executable code somewhere, opaque.expression<func<...>>
, on other hand, expression tree, kind of ast.
when write lambda, compiler generates different code depending on whether you're assigning lambda func<...>
or expression<func<...>>
. in first case, compile lambda , generate delegate. in second case, emit expression tree.
for in-depth explanation, can read eric lippert's series lambda expressions vs. anonymous methods: part 1, part 2, part 3, part 4, part 5
Comments
Post a Comment