如何GetType()。具有自定义属性的GetFields?

时间:2011-12-01 19:32:14

标签: c# .net reflection typedescriptor

这个旧代码使用反射

返回方法调用中使用属性修饰的字段列表

有没有办法用TypeDescripter或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;
    }

2 个答案:

答案 0 :(得分:4)

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();
}

如果您可以返回IEnumerable<FieldInfo>,则应该可以直接返回选择。

答案 1 :(得分:1)

怎么样:

return type
    .GetFields()
    .Where(fi => 
        fi.GetCustomAttributes(attr.GetType(), false).Length > 0 
        && !(onlyFromType && fi.DeclaringType != type))
    .ToArray();