Skip to content

Instantly share code, notes, and snippets.

@EduVencovsky
Last active June 17, 2021 08:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EduVencovsky/1b3a0fd5b356cba752f7993ac130cab4 to your computer and use it in GitHub Desktop.
Save EduVencovsky/1b3a0fd5b356cba752f7993ac130cab4 to your computer and use it in GitHub Desktop.
Helper to get custom attributes from a property with Blazor
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
namespace ADD_YOUR_NAME_SPACE_HERE
{
public static class CustomAttributeHelper
{
public static MemberInfo GetExpressionMember<T>(Expression<Func<T>> accessor)
{
var accessorBody = accessor.Body;
// Unwrap casts to object
if (accessorBody is UnaryExpression unaryExpression
&& unaryExpression.NodeType == ExpressionType.Convert
&& unaryExpression.Type == typeof(object))
{
accessorBody = unaryExpression.Operand;
}
if (!(accessorBody is MemberExpression memberExpression))
{
throw new ArgumentException($"The provided expression contains a {accessorBody.GetType().Name} which is not supported. {nameof(FieldIdentifier)} only supports simple member accessors (fields, properties) of an object.");
}
return memberExpression.Member;
}
public static IEnumerable<Attribute> GetExpressionCustomAttributes<T>(Expression<Func<T>> accessor)
{
return GetExpressionMember(accessor).GetCustomAttributes();
}
public static IEnumerable<TAttribute> GetExpressionCustomAttributes<T, TAttribute>(Expression<Func<T>> accessor, bool inherit = false)
where TAttribute : Attribute
{
return GetExpressionMember(accessor).GetCustomAttributes<TAttribute>(inherit);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment