如何获取特定属性的PropertyInfo?

ten*_*npn 77 c# reflection

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

foreach(PropertyInfo p in typeof(MyObject).GetProperties())
{
    if ( p.Name == "MyProperty") { return p }
}
Run Code Online (Sandbox Code Playgroud)

但必须有办法做类似的事情

typeof(MyProperty) as PropertyInfo
Run Code Online (Sandbox Code Playgroud)

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

干杯.

Mar*_*ell 130

有一个.NET 3.5方式lambdas/Expression不使用字符串...

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 一个问题:在提取.Body属性之前,为什么对"body是LambdaExpression"进行测试?选择器不是一个LambdaExpression吗? (4认同)

Kev*_*ski 55

您可以使用nameof()属于C#6 的新运算符,并在Visual Studio 2015中提供.此处有更多信息.

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

PropertyInfo result = typeof(MyObject).GetProperty(nameof(MyObject.MyProperty));
Run Code Online (Sandbox Code Playgroud)

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

  • 如果您的示例以“PropertyInfo result =”而不是“var result =”开头,那么可以说会更清晰一些。 (2认同)

Voj*_*vic 12

你可以这样做:

typeof(MyObject).GetProperty("MyProperty")
Run Code Online (Sandbox Code Playgroud)

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

  • 因为它不是在编译时评估的?如果我更改了我的属性名称或者错误输入了代码运行之前我不知道的字符串. (36认同)