【发布时间】:2010-12-29 13:19:16
【问题描述】:
可能的重复:
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 post 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);
}
【问题讨论】:
-
我认为它应该保持打开状态。 @GvS 的答案非常好,适用于在 asp.net mvc 应用程序中执行此类工作。我们标记为骗子的其他问题都没有他的答案。
-
另见stackoverflow.com/questions/671968/…——如果你想要嵌套属性(即
Thing1.Thing2fromo => o.Thing1.Thing2——见my attempt for an alternative
标签: c# .net lambda expression