开发者

How do I get the value from an anonymous expression?

For sake of simplicity, imagine the following code:

I want to create a Foo:

public class Foo
{
    public string Bar { get; set; }
}

And pass it to a special Html Helper method:

Html.SomeFunction(f => f.Bar);

Which is defined as:

public string SomeFunction<TModel, TValue&开发者_运维技巧gt;(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)

I want to get the value of Bar inside of this function, but have absolutely no idea how to get it.


Simply compile the expression and get the value.

Func<TModel, TValue> method = expression.Compile();

TValue value = method(html.ViewData.Model);
// might be a slightly different property, but you can get the ViewModel 
// from the HtmlHelper object. 


You will need to call Compile() on the expression to get the Func and then execute that.

public string SomeFunction<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
    TValue valueOfBar = expression.Compile()(html.Model); // Assumes Model is accessible from html.

    // Do stuff
}

Side note: If there isn't any need for the dynamic expressions or expression analysis you might as well pass the Func directly in instead.


For those that are using expression without MVT Model, one would obtain name and value of property in a following way.

public static string Meth<T>(Expression<Func<T>> expression)
{
    var name = ((MemberExpression)expression.Body).Member.Name;
    var value = expression.Compile()();
    return string.Format("{0} - {1}", name, value);
}

use:

Meth(() => YourObject.Property);


in Microsoft.AspNetCore.Mvc.Rendering there is helpfull valuefor method;

public static string ValueFor<TModel, TResult>(this IHtmlHelper htmlHelper, Expression<Func<TModel, TResult>> expression);

public string SomeFunction<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression){
var valueOfExpression = html.ValueFor(expression); 
//do your stuff
}


Using Compile() will use the Roslyn compiler-framework and will emit MSIL-code that will be dynamically loaded into your application. This executable code takes up memory, and in contrast to "normal" memory it is not subject to garbage collection nor can you free it yourself. If you do this too frequently (like regularly during SQL generation) you will run out of memory eventually. I ran into this issue and open-sourced my solutions as an open-source library:

https://www.nuget.org/packages/MiaPlaza.ExpressionUtils

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜