Possible Duplicates:
Get method name and type using lambda expression
Can I use Expression<Func<T, bool>> and reliably see which properties are referenced in the Func<T, bool>?
嗨,
我想要一个方法,我可以像这样使用
<% Html.TextBoxFor(x=>x.Property, Helper.GetAttributes<ViewModel>(x=>x.PropertyA)) %>
方法头看起来像这样
public static Dictionary<string, string> GetAttributeValues<T>(Expression<Func<T, object>> myParam)
但是我如何找到PropertyA的名称呢?在返回正确的属性之前我需要做一些检查。 提前致谢..
干杯
PS:感谢driis帖子How to get names from expression property?我找到了解决办法
是
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);
}
最佳答案
创建 ModelMetadata 的实例类:
var data = ModelMetadata.FromLambdaExpression<T, object>(myParam);
现在您可以获得有关模型上使用的属性的所有所需信息:
var propName = data.PropertyName;
var label = data.DisplayName;
关于c# - 如何从表达式属性中获取名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4554427/