Cómo getType (). GetFields con un atributo personalizado?
-
27-10-2019 - |
Pregunta
Este antiguo código devuelve una lista de campos decorados con un atributo en una llamada de método utilizando reflexión
¿Hay alguna forma de reemplazarlo con Typedescripter o 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;
}
Solución
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();
}
Si puedes devolver un IEnumerable<FieldInfo>
, debería poder devolver la selección directamente.
Otros consejos
Qué tal si:
return type
.GetFields()
.Where(fi =>
fi.GetCustomAttributes(attr.GetType(), false).Length > 0
&& !(onlyFromType && fi.DeclaringType != type))
.ToArray();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow