Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to GetType().GetFields with a custom attribute?

this old code returns a list of fields decorated with an attribute in a method call using reflection

Is there a way to replace it with TypeDescripter or LINQ ?

    public static FieldInfo[] GetFieldsWithAttribute(Type type, Attribute attr, bool onlyFromType)
    {
        System.Reflection.FieldInfo[] infos = type.GetFields();
        int cnt = 0;
        foreach (System.Reflection.FieldInfo info in infos)
        {
            if (info.GetCustomAttributes(attr.GetType(), false).Length > 0)
            {
                if (onlyFromType && info.DeclaringType != type)
                    continue;

                cnt++;
            }
        }

        System.Reflection.FieldInfo[] rc = new System.Reflection.FieldInfo[cnt];
        // now reset !
        cnt = 0;

        foreach (System.Reflection.FieldInfo info in infos)
        {
            if (info.GetCustomAttributes(attr.GetType(), false).Length > 0)
            {
                if (onlyFromType && info.DeclaringType != type)
                    continue;

                rc[cnt++] = info;
            }
        }

        return rc;
    }
like image 537
Kumar Avatar asked Dec 01 '11 19:12

Kumar


2 Answers

public static FieldInfo[] GetFieldsWithAttribute(Type type, Attribute attr, bool onlyFromType)
{
    System.Reflection.FieldInfo[] infos = type.GetFields();
    var selection = 
       infos.Where(info =>
         (info.GetCustomAttributes(attr.GetType(), false).Length > 0) &&
         ((!onlyFromType) || (info.DeclaringType == type)));

    return selection.ToArray();
}

If you can return an IEnumerable<FieldInfo>, you should be able to return selection directly.

like image 190
vc 74 Avatar answered Oct 14 '22 09:10

vc 74


How about:

return type
    .GetFields()
    .Where(fi => 
        fi.GetCustomAttributes(attr.GetType(), false).Length > 0 
        && !(onlyFromType && fi.DeclaringType != type))
    .ToArray();
like image 30
spender Avatar answered Oct 14 '22 10:10

spender