反射 - 获取属性名称 [英] Reflection - get property name
本文介绍了反射 - 获取属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在不使用魔法字符串的情况下将属性名称传递给函数.
I'd like to pass property names to a function without using of magic strings.
类似于:
Get<ObjectType>(x=>x.Property1);
其中 Property1 是 ObjectType 类型的属性.
where Property1 is a property of type ObjectType.
方法实现是什么样的?
推荐答案
这可以使用表达式来实现:
This can be achieved using Expressions:
// requires object instance, but you can skip specifying T
static string GetPropertyName<T>(Expression<Func<T>> exp)
{
return (((MemberExpression)(exp.Body)).Member).Name;
}
// requires explicit specification of both object type and property type
static string GetPropertyName<TObject, TResult>(Expression<Func<TObject, TResult>> exp)
{
// extract property name
return (((MemberExpression)(exp.Body)).Member).Name;
}
// requires explicit specification of object type
static string GetPropertyName<TObject>(Expression<Func<TObject, object>> exp)
{
var body = exp.Body;
var convertExpression = body as UnaryExpression;
if(convertExpression != null)
{
if(convertExpression.NodeType != ExpressionType.Convert)
{
throw new ArgumentException("Invalid property expression.", "exp");
}
body = convertExpression.Operand;
}
return ((MemberExpression)body).Member.Name;
}
用法:
var x = new ObjectType();
// note that in this case we don't need to specify types of x and Property1
var propName1 = GetPropertyName(() => x.Property1);
// assumes Property2 is an int property
var propName2 = GetPropertyName<ObjectType, int>(y => y.Property2);
// requires only object type
var propName3 = GetPropertyName<ObjectType>(y => y.Property3);
更新:修复了返回值类型的属性的GetPropertyName
.
Update: fixed GetPropertyName<TObject>(Expression<Func<TObject, object>> exp)
for properties returning value types.
这篇关于反射 - 获取属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文