Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting attribute from overridden property via a linq Expression

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.

like image 232
Jero Avatar asked Apr 25 '12 22:04

Jero


1 Answers

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));
like image 133
nemesv Avatar answered Sep 21 '22 16:09

nemesv