我想获取特定属性的 PropertyInfo。我可以使用:
foreach(PropertyInfo p in typeof(MyObject).GetProperties())
{
if ( p.Name == "MyProperty") { return p }
}
但必须有一种方法可以做类似
的事情typeof(MyProperty) as PropertyInfo
有吗?还是我一直在进行类型不安全的字符串比较?
干杯。
最佳答案
有一个 .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();
}
}
}
关于c# - 如何获取特定属性的 PropertyInfo?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/491429/