反射 - 获取属性名称
问题描述:
我想将属性名称传递给函数而不使用魔法字符串。反射 - 获取属性名称
是这样的:
Get<ObjectType>(x=>x.Property1);
其中Property1是类型对象类型的属性。
该方法的实现是什么样的?
答
这可以使用表达式来实现:
// 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<TObject>(Expression<Func<TObject, object>> exp)
为属性返回值类型。
答
class Foo
{
public string Bar { get; set; }
}
class Program
{
static void Main()
{
var result = Get<Foo, string>(x => x.Bar);
Console.WriteLine(result);
}
static string Get<T, TResult>(Expression<Func<T, TResult>> expression)
{
var me = expression.Body as MemberExpression;
if (me != null)
{
return me.Member.Name;
}
return null;
}
}
是否有机会在没有创建实例并且没有空括号的情况下使其工作? Just(x => x.Prop1) – user137348 2011-01-11 12:07:10