Last active
June 17, 2021 08:01
-
-
Save EduVencovsky/1b3a0fd5b356cba752f7993ac130cab4 to your computer and use it in GitHub Desktop.
Helper to get custom attributes from a property with Blazor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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