【发布时间】:2013-01-03 03:42:24
【问题描述】:
在 .net FrameWork 3.5 中,我们可以使用下面提到的代码获取属性信息。
using System;
using System.Linq.Expressions;
using System.Reflection;
class Foo
{
public string Bar { get; set; }
}
static class Program
{
static void Main()
{
PropertyInfo prop = PropertyHelper<Foo>.GetProperty(x => x.Bar);
}
}
public static class PropertyHelper<T>
{
public static PropertyInfo GetProperty<TValue>(
Expression<Func<T, TValue>> selector)
{
Expression body = selector;
if (body is LambdaExpression)
{
body = ((LambdaExpression)body).Body;
}
switch (body.NodeType)
{
case ExpressionType.MemberAccess:
return (PropertyInfo)((MemberExpression)body).Member;
default:
throw new InvalidOperationException();
}
}
}
这也可以通过创建类的实例并访问属性成员来完成。那么Property Info有什么优势呢?
【问题讨论】:
-
使用您引用的示例代码,在这种情况下使用表达式树主要是为了避免在您想要获取属性信息时在代码中硬编码属性名称。它在简化重构方面大有帮助。
标签: c# c#-4.0 c#-3.0 expression c#-2.0