我从lambda表达式(使用System.Linq.Expressions.Expression
)获取表达式树,以获取在子类中被覆盖的属性的PropertyInfo。似乎这种技术总是为我提供基类中的属性的PropertyInfo而不是重写的属性。
要获取正确的PropertyInfo,一种解决方法是使用反射(使用原始(错误的)PropertyInfo的名称),例如:var correctPropertyInfo = mySubClassObject.GetType().GetProperty(wrongPropertyInfo.Name);
下面是说明此(.NET Fiddle)的代码:
using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;
public class Program
{
public static void Main()
{
var b = new B();
var propertyInfo = GetPropertyInfo(b.GetProperty());
Console.WriteLine("=== The wrong property ===");
PrintProperty(propertyInfo);
propertyInfo = b.GetType().GetProperty(propertyInfo.Name);
Console.WriteLine("\r\n=== The right property ===");
PrintProperty(propertyInfo);
}
private static PropertyInfo GetPropertyInfo<T>(Expression<Func<T>> propertyExpression)
{
var expr = (MemberExpression)propertyExpression.Body;
return (PropertyInfo)expr.Member;
}
private static void PrintProperty(PropertyInfo propertyInfo)
{
Console.WriteLine("DeclaringType: " + propertyInfo.DeclaringType);
Console.WriteLine("DisplayName: " + propertyInfo.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName);
}
}
public class A
{
public virtual string MyProperty { get; set; }
}
public class B : A
{
[DisplayName("Overridden Method")]
public override string MyProperty { get; set; }
public Expression<Func<string>> GetProperty()
{
return () => MyProperty;
}
}
以下是输出:
=== The wrong property ===
DeclaringType: A
DisplayName:
=== The right property ===
DeclaringType: B
DisplayName: Overridden Method
为什么我得到了错误的PropertyInfo,并且有一种方法可以立即获得正确的信息而无需执行其他“变通方法”步骤?