如何获取特定属性的PropertyInfo?

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


foreach(PropertyInfo p in typeof(MyObject).GetProperties())

{

    if ( p.Name == "MyProperty") { return p }

}

但是必须有一种方法可以做类似的事情


typeof(MyProperty) as PropertyInfo

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


干杯。


FFIVE
浏览 1376回答 3
3回答

斯蒂芬大帝

您可以使用新的nameof()操作符是在Visual Studio的C#6部分,2015年提供更多信息这里。对于您的示例,您将使用:PropertyInfo result = typeof(MyObject).GetProperty(nameof(MyObject.MyProperty));编译器将转换nameof(MyObject.MyProperty)为字符串“ MyProperty”,但由于Visual Studio,ReSharper等知道如何重构nameof()值,因此您无需重构就可以重构属性名,从而获得了好处。

Qyouu

带有lambdas /的.NET 3.5方式Expression不使用字符串...using System;using System.Linq.Expressions;using System.Reflection;class Foo{&nbsp; &nbsp; public string Bar { get; set; }}static class Program{&nbsp; &nbsp; static void Main()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; PropertyInfo prop = PropertyHelper<Foo>.GetProperty(x => x.Bar);&nbsp; &nbsp; }}public static class PropertyHelper<T>{&nbsp; &nbsp; public static PropertyInfo GetProperty<TValue>(&nbsp; &nbsp; &nbsp; &nbsp; Expression<Func<T, TValue>> selector)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Expression body = selector;&nbsp; &nbsp; &nbsp; &nbsp; if (body is LambdaExpression)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; body = ((LambdaExpression)body).Body;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; switch (body.NodeType)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case ExpressionType.MemberAccess:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return (PropertyInfo)((MemberExpression)body).Member;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new InvalidOperationException();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

森栏

你可以这样做:typeof(MyObject).GetProperty("MyProperty")但是,由于C#没有“符号”类型,因此没有什么可以帮助您避免使用字符串。顺便说一下,为什么将这种类型称为不安全类型?
打开App,查看更多内容
随时随地看视频慕课网APP