开发者

How to get names from expression property? [duplicate]

开发者 https://www.devze.com 2023-02-02 03:20 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicates: Get method name and type using lambda expression
This question already has answers here: Closed 12 years ago.

Possible Duplicates:

Get method name and type using lambda expression

Can I use Expression<Fun开发者_C百科c<T, bool>> and reliably see which properties are referenced in the Func<T, bool>?

Hi,

I want to have a method, which I can use like this

<% Html.TextBoxFor(x=>x.Property, Helper.GetAttributes<ViewModel>(x=>x.PropertyA)) %>

The method header looks like this

public static Dictionary<string, string> GetAttributeValues<T>(Expression<Func<T, object>> myParam)

but how do i find out the name of PropertyA? i need to do some checks before returning the right attributes. thanks in advance..

cheers

PS: thanks to driis post How to get names from expression property? i found the solution

it is

public static Dictionary<string, string> GetAttributeValues<T>(Expression<Func<T, object>> myParam)
{
    var item = myParam.Body as UnaryExpression;
    var operand = item.Operand as MemberExpression;
    Log.Debug(operand.Member.Name);
}


Create an instance of a ModelMetadata class:

var data = ModelMetadata.FromLambdaExpression<T, object>(myParam);

And now you can get all the information you need, with respect to attributes used on your model:

var propName = data.PropertyName;
var label = data.DisplayName;


That could be:

string propertyName = ((MemberExpression) myParam.Body).Member.Name;

In production code, you should probably check the Expression type before the cast and throw an appropiate exception if the expression passed in is not MemberExpression.

0

精彩评论

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