Getting attribute from overridden property via a linq Expression
Asked Answered
I

1

6

I'm trying to use GetCustomAttributes() to get an attribute defined on a property. The issue is that the property is an overridden one and I can't work out how to extract the overridden one from the expression. I can only work out how to get the base class's one.

Here's some code

public class MyAttribute : Attribute 
{
  //... 
}

public abstract class Text
{
  public abstract string Content {get; set;}
}

public class Abstract : Text
{
  [MyAttribute("Some Info")]
  public override string Content {get; set;}
}

Now I am trying to get the MyAttribute out of the abstract class. But I need to get it via an Expression. This is what I have been using:

Expression<Func<Abstract, string>> expression =  c => c.Content;
Expression exp = expression.Body;
MemberInfo memberType = (exp as MemberExpression).Member;

var attrs = Attribute.GetCustomAttributes(memberType, true);

Unfortunately atts ends up as empty. The problem is that menberType ends up being for Text.Content instead of the Abstract.Content class. So when I get the attributes, it returns nothing.

Incompletion answered 25/4, 2012 at 22:40 Comment(0)
A
4

It is not working because the MemberExpression ignores the overrides and returns the property form the base type Text that's why you don't find your attribute.

You can read about this problem here: How to get the child declaring type from an expression?

However you have all the information in the expression and you can get your attribute with a little more reflection (quick and dirty sample):

Expression<Func<Abstract, string>> expression = (Abstract c) => c.Content;
Expression exp = expression.Body;
MemberInfo memberType = (exp as MemberExpression).Member;

var attrs = Attribute.GetCustomAttributes(
expression.Parameters[0].Type.GetProperty(memberType.Name));
Alfilaria answered 26/4, 2012 at 5:52 Comment(2)
Thanks for the link to the other question. I searched for something similar but didn't find that one.Incompletion
That solution you gave is the work around I have been using up till now so nice to get some independent support for that one :-) ThanksIncompletion

© 2022 - 2024 — McMap. All rights reserved.