[英]How to get the PropertyInfo of a specific property?
我想获取特定属性的 PropertyInfo。 我可以使用:
foreach(PropertyInfo p in typeof(MyObject).GetProperties())
{
if ( p.Name == "MyProperty") { return p }
}
但是必须有一种方法可以做类似的事情
typeof(MyProperty) as PropertyInfo
有没有? 还是我一直在进行类型不安全的字符串比较?
干杯。
有一个使用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();
}
}
}
您可以使用属于C#6的新nameof()
运算符,并在Visual Studio 2015中提供。 此处有更多信息。
对于您的示例,您将使用:
PropertyInfo result = typeof(MyObject).GetProperty(nameof(MyObject.MyProperty));
编译器会将nameof(MyObject.MyProperty)
转换为字符串“MyProperty”,但您可以获得能够重构属性名称而不必记住更改字符串的好处,因为Visual Studio,ReSharper等知道如何重构nameof()
值。
你可以这样做:
typeof(MyObject).GetProperty("MyProperty")
但是,由于C#没有“符号”类型,因此没有什么可以帮助您避免使用字符串。 顺便说一句,为什么你称这种类型不安全?
这可能是最好的方法:
public static class TypeExtensions
{
public static PropertyInfo? GetProperty<T, TValue>(this T type, Expression<Func<T, TValue>> selector) where T : class
{
Expression expression = selector.Body;
return expression.NodeType == ExpressionType.MemberAccess ? (PropertyInfo)((MemberExpression)expression).Member : null;
}
}
用法:
myObject.GetProperty(opt => opt.PropertyName);
反射用于运行时类型评估。 因此,在编译时无法验证字符串常量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.