Skip to content

Instantly share code, notes, and snippets.

@takeshik
Created February 18, 2013 09:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takeshik/4976300 to your computer and use it in GitHub Desktop.
Save takeshik/4976300 to your computer and use it in GitHub Desktop.
get Attribute[] from lambda
public static Attribute[] GetAttributes(Expression expr)
{
switch (expr.NodeType)
{
case ExpressionType.MemberAccess:
return Attribute.GetCustomAttributes(((MemberExpression) expr).Member);
case ExpressionType.Invoke:
return Attribute.GetCustomAttributes(((MethodCallExpression) expr).Method);
case ExpressionType.Index:
return Attribute.GetCustomAttributes(((IndexExpression) expr).Indexer);
default:
return new NotSupportedException(expr.NodeType);
}
}
public static Attribute[] GetAttributes<T>(Expression<Func<object>> selector)
{
return GetAttributes(selector.Body);
}
public static Attribute[] GetAttributes<T>(this T recv, Expression<Func<T, object>> selector)
{
return GetAttributes(selector.Body);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment