How to get member attribute data with FastMember

using the FastMember library from NuGet, I can find all type members that are decorated with a specific attribute using this code:

var accessor = TypeAccessor.Create(typeof (MyData));
var decoratedMembers = accessor.GetMembers().Where(x=>x.IsDefined(typeof(MyDecorationAttribute));

This is very good and good, but I now need to get a specific instance MyDecorationAttributefor each member in decoratedMembers MemberSet, and as far as I can see, there is no way to do this.

Am I missing something? Perhaps there is another library that I should use to get attribute data for each member, or it will be reflected in Reflection in this case.

+4
source share
2 answers

First of all, Mark, thank you very much for the AWESOME library!

-, , , ...

- MemberInfo , "" , .

http://www.codeproject.com/Articles/80343/Accessing-private-members.aspx

public static class SillyMemberExtensions
{
    public static T GetPrivateField<T>(this object obj, string name)
    {
        BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
        Type type = obj.GetType();
        FieldInfo field = type.GetField(name, flags);
        return (T)field.GetValue(obj);
    }

    public static T GetPrivateProperty<T>(this object obj, string name)
    {
        BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
        Type type = obj.GetType();
        PropertyInfo field = type.GetProperty(name, flags);
        return (T)field.GetValue(obj, null);
    }

    public static MemberInfo GetMemberInfo(this FastMember.Member member)
    {
        return GetPrivateField<MemberInfo>(member, "member");
    }

    public static T GetMemberAttribute<T>(this FastMember.Member member) where T : Attribute
    {
        return GetPrivateField<MemberInfo>(member, "member").GetCustomAttribute<T>();
    }
}

:

if (m.IsDefined(typeof(MyCustomAttribute)))
{
    var attr = m.GetMemberAttribute<MyCustomAttribute>();
    if (attr.SomeCustomParameterInTheAttribute >= 10)
        return "More than 10";
}
+2

, Private Member, . SlowMember

:

var reflectionService = new ReflectionService();
var description = reflectionService.GetObjectDescription(_complexClass, true);
var attributeDescription = description.MemberDescriptions
            .FirstOrDefault(f => f.Name == "Text")
            .AttributeDescriptions.FirstOrDefault(ad => ad.Name == "Required");

Github: https://github.com/efaruk/slow-member

0

All Articles