如何获取特定属性的PropertyInfo?

时间:2009-01-29 12:34:57

标签: c# reflection

我想获取特定属性的PropertyInfo。我可以用:

foreach(PropertyInfo p in typeof(MyObject).GetProperties())
{
    if ( p.Name == "MyProperty") { return p }
}

但必须有办法做类似

的事情
typeof(MyProperty) as PropertyInfo

有吗?还是我坚持做一个类型不安全的字符串比较?

干杯。

4 个答案:

答案 0 :(得分:129)

使用lambdas / Expression的.NET 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();
        }
    }
}

答案 1 :(得分:50)

您可以使用属于C#6且在Visual Studio 2015中可用的新nameof()运算符。更多信息here

对于您的示例,您将使用:

PropertyInfo result = typeof(MyObject).GetProperty(nameof(MyObject.MyProperty));

编译器会将nameof(MyObject.MyProperty)转换为字符串&#34; MyProperty&#34;但是您可以获得能够重构属性名称而不必记住更改字符串的好处,因为Visual Studio,ReSharper等知道如何重构nameof()值。

答案 2 :(得分:11)

你可以这样做:

typeof(MyObject).GetProperty("MyProperty")

但是,由于C#没有“符号”类型,因此没有什么可以帮助您避免使用字符串。顺便说一下,为什么你称这种类型不安全?

答案 3 :(得分:1)

反射用于运行时类型评估。所以你的字符串常量在编译时无法验证。

相关问题