C# 如何从表达式属性获取名称?

C# 如何从表达式属性获取名称?,c#,.net,lambda,expression,C#,.net,Lambda,Expression,可能的重复项: 嗨 我想有一个方法,我可以这样使用 <% Html.TextBoxFor(x=>x.Property, Helper.GetAttributes<ViewModel>(x=>x.PropertyA)) %> public static Dictionary<string, string> GetAttributeValues<T>(Expression<Func<T, object>> my

可能的重复项:

我想有一个方法,我可以这样使用

<% Html.TextBoxFor(x=>x.Property, Helper.GetAttributes<ViewModel>(x=>x.PropertyA)) %>
public static Dictionary<string, string> GetAttributeValues<T>(Expression<Func<T, object>> myParam)
x.Property,Helper.GetAttributes(x=>x.PropertyA))%>
方法头如下所示

<% Html.TextBoxFor(x=>x.Property, Helper.GetAttributes<ViewModel>(x=>x.PropertyA)) %>
public static Dictionary<string, string> GetAttributeValues<T>(Expression<Func<T, object>> myParam)
公共静态字典GetAttributeValue(表达式myParam)
但是我怎样才能找到房地产的名字呢?在返回正确的属性之前,我需要做一些检查。 提前谢谢

干杯

PS:多亏了driis post,我找到了解决方案

是的

公共静态字典GetAttributeValue(表达式myParam)
{
var item=myParam.Body作为一元表达式;
变量操作数=项。操作数作为MemberExpression;
Log.Debug(操作数.成员.名称);
}
可能是:

string propertyName = ((MemberExpression) myParam.Body).Member.Name;
在生产代码中,您可能应该在强制转换之前检查表达式类型,如果传入的表达式不是MemberExpression,则引发appropiate异常

创建类的实例:


感谢您的快速响应,但我收到错误InvalidCastexception,无法从“System.Linq.Expressions.UnaryExpression”转换为“System.Ling.Expressions.MemberExpression”再次感谢,您对MemberExpression的提示向我展示了解决此问题的正确方法:-)我已更新了我的原始帖子,我认为它应该保持打开状态@GvS的答案非常好,适用于在asp.net mvc应用程序中执行此类工作。我们标记为重复的其他问题都没有他的答案。另请参见——如果您想要嵌套属性(即
Thing1.Thing2
from
o=>o.Thing1.Thing2
,请参见
var propName = data.PropertyName;
var label = data.DisplayName;