gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:17:18 24 4
gpt4 key购买 nike

这段旧代码在使用反射的方法调用中返回一个用属性修饰的字段列表

有没有办法用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com