如何获取特定属性的PropertyInfo?

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

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

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

 typeof(MyProperty) as PropertyInfo 

在那儿? 或者我坚持做一个types不安全的string比较?

干杯。

您可以使用Visual Studio 2015中可用的C#6的新nameof()运算符。更多信息请nameof() 此处 。

对于你的例子,你可以使用:

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

编译器会将nameof(MyObject.MyProperty)转换为string“MyProperty”,但是您可以重新获得属性名称的好处,而不必记住更改string,因为Visual Studio,ReSharper等知道如何重构nameof()值。

有一个.NET 3.5的方式与lambdaexpression式/不使用string…

 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(); } } } 

你可以这样做:

 typeof(MyObject).GetProperty("MyProperty") 

但是,由于C#没有“符号”types,因此没有任何东西可以帮助您避免使用string。 顺便说一句,你为什么称这种types不安全?

reflection用于运行时types评估。 所以你的string常量不能在编译时被validation。