这段旧代码在使用反射的方法调用中返回一个用属性修饰的字段列表
有没有办法用 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/