How to get the Attribute data of a Member with FastMember

房东的猫 提交于 2019-12-04 11:25:23

First and foremost - Marc, thank you very much for an AWESOME library!

Second, please forgive me Marc, for I am about to sin...

I have had the same problem - a desire to access a MemberInfo about the member, but library lets me "sniff" it, but not to access it.

With a bit of help from 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>();
    }
}

Usage:

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

This is not alternative to fast-member but, it has Private Member support, Attribute support and Caching. Here is SlowMember

Usage:

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 Repository: https://github.com/efaruk/slow-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!