public class GetModelProperty
{
public static string GetPropertyDesc(Type objectType, string propertyName)
{
try
{
var first = objectType.GetProperty(propertyName).GetCustomAttributes(typeof(DataFieldAttribute), false).FirstOrDefault(); //objectType.GetProperty(propertyName).GetCustomAttributes(typeof(DataFieldAttribute),false).FirstOrDefault();
return ((DataFieldAttribute)first).DescName;
}
catch (Exception ex)
{
ErrorLog.Write("分解对象值出错",ex);
}
return "未知属性名称";
}
public static string GetPropertyName<T>(Expression<Func<T, object>> expr)
{
var rtn = "";
if (expr.Body is UnaryExpression)
{
rtn = ((MemberExpression)((UnaryExpression)expr.Body).Operand).Member.Name;
}
else if (expr.Body is MemberExpression)
{
rtn = ((MemberExpression)expr.Body).Member.Name;
}
else if (expr.Body is ParameterExpression)
{
rtn = ((ParameterExpression)expr.Body).Type.Name;
}
return rtn;
}
}
调用:
GetModelProperty target = new GetModelProperty(); // TODO: 初始化为适当的值
FloorsTO m=new FloorsTO();
Type objectType = typeof(FloorsTO); // TODO: 初始化为适当的值
string propertyName = "";
string expected = string.Empty; // TODO: 初始化为适当的值
string actual;
actual = GetModelProperty.GetPropertyName<FloorsTO>(c => c.TotalPower);
var ddd = GetModelProperty.GetPropertyDesc(typeof(FloorsTO), actual);
Assert.AreEqual(expected, actual);
Assert.Inconclusive("验证此测试方法的正确性。");
前提,要自己定义一个属性:
public class DataFieldAttribute:Attribute
{
public string DescName { get; set; }
}