我具有以下设置,并且我试图通过访问表达式并尝试从MemberExpression中提取PropertyInfo
来获取属性信息。但是PropertyInfo
不会继承属性(即DisplayAttribute
)。
sealed class MemberExpressionVisitor : ExpressionVisitor
{
private readonly Expression _expression;
private List<MemberInfo> _members;
public MemberExpressionVisitor(Expression expression)
{
_expression = expression;
}
protected override Expression VisitMember(MemberExpression node)
{
// Problem:
// node.Member does not have DisplayAttribute in node.Member.CustomAttributes
_members = new[] {node.Member}.Concat(_members).ToList();
return base.VisitMember(node);
}
public void Accept(out List<MemberInfo> members)
{
_members = new List<MemberInfo>();
Visit(_expression);
members = _members;
}
}
interface IParent
{
string IndexName { get; set; }
}
class Child : IParent
{
[Display(Name = "Name_Not_IndexName")]
public string IndexName { get; set; }
}
class Test<T> where T: class, IParent {
public Test()
{
Expression<Func<T, string>> expr = x => x.IndexName;
new MemberExpressionVisitor(expr).Accept(out _);
}
}
class Program
{
static void Main(string[] args)
{
new Test<Child>();
}
}