使用反射常用方法之一
public static string GetPropertyName<T>(Expression<Func<T, object>> expression)
{
var rtn = "";
if (expression.Body is UnaryExpression)
{
rtn = ((MemberExpression)((UnaryExpression)expression.Body).Operand).Member.Name;
}
else if (expression.Body is MemberExpression)
{
rtn = ((MemberExpression)expression.Body).Member.Name;
}
else if (expression.Body is ParameterExpression)
{
rtn = ((ParameterExpression)expression.Body).Type.Name;
}
else
throw new Exception("无法获取属性名称");
return rtn;
}
使用示例
GetPropertyName<TestClass>(val => val.ID)
//返回"ID"
//类示例
class TestClass {
public string ID {get; set;}
}