Frage

Dieser alte Code gibt eine Liste von Feldern zurück, die mit einem Attribut in einem Methodenaufruf mit Reflexion dekoriert sind

Gibt es eine Möglichkeit, es durch typedescripter oder linq zu ersetzen?

    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;
    }
War es hilfreich?

Lösung

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

Wenn Sie eine zurückgeben können IEnumerable<FieldInfo>, Sie sollten in der Lage sein, die Auswahl direkt zurückzugeben.

Andere Tipps

Wie wäre es mit:

return type
    .GetFields()
    .Where(fi => 
        fi.GetCustomAttributes(attr.GetType(), false).Length > 0 
        && !(onlyFromType && fi.DeclaringType != type))
    .ToArray();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top