C# 为什么要为child';s重写的属性显示父项';s属性
让我们假设我们有两个类C# 为什么要为child';s重写的属性显示父项';s属性,c#,.net,reflection,attributes,linq-expressions,C#,.net,Reflection,Attributes,Linq Expressions,让我们假设我们有两个类 class A{ public abstract int Prop1 {get; set;} } 这是我的孩子 class Child : A{ [CustomAttr(someval)] override public int Prop1 {get; set;} } 因此,在我的代码后面,我需要获取这个自定义属性的val bool haveCustomAttr(IExpression<Func<Child, int>> p
class A{
public abstract int Prop1 {get; set;}
}
这是我的孩子
class Child : A{
[CustomAttr(someval)]
override public int Prop1 {get; set;}
}
因此,在我的代码后面,我需要获取这个自定义属性的val
bool haveCustomAttr(IExpression<Func<Child, int>> property){
return ((MemberExpression)property.Body).Member.GetCustomAttributes(typeof(CustomAttr)).Any();
}
返回false
是因为((MemberExpression)property.Body).Member
是因为某种原因A.Prop1
而不是Child.Prop1
可以用这样更先进的结构进行修复
((MemberExpression)property.Body).Expression.Type.GetMember(((MemberExpression)property.Body).Member
.Name)[0].GetCustomAttributes(typeof(CustomAttr), false).Any();
但我仍然不清楚,如果明确地说它是来自
Child
类的表达式,为什么最初会将这个表达式作为基类。有人能给我解释一下这背后的逻辑吗?这不是表达式树所特有的;property.Body
中的调用最终将编译为对a.Prop1
的调用,即使是通过类型为Child
的表达式调用。该方法的vtable槽单独位于A
和A
中。如果Child
使用相同名称的new
声明对此进行隐藏,则调用将转到Child
。
((MemberExpression)property.Body).Expression.Type.GetMember(((MemberExpression)property.Body).Member
.Name)[0].GetCustomAttributes(typeof(CustomAttr), false).Any();