c# - 如何使用自定义属性获取 GetType().GetFields?

标签 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;
    }

最佳答案

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> ,您应该能够直接返回选择。

关于c# - 如何使用自定义属性获取 GetType().GetFields?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8347182/

相关文章:

c# - 如何检查 appSettings 键是否存在?

c# - 如何将控件的外观转换为图像?

.net - 您通过单元测试测试什么?

c# - 使用可能不存在的反射设置属性

c# - 带有绑定(bind)的 MVVM 菜单栏

c# - 在datagridview c#中调整行号列的大小

c# - 两个使用嵌套在一起

asp.net - UseHttpsRedirection 和 UseHsts 有什么区别

c# - 如何确定类型是否实现了 C# 反射的接口(interface)

java - 使用 Java NetBeans 制作我自己的 GUI 构建器