jeudi 5 mars 2020

FieldInfo.GetValue() returns null for a nested static class public static fields

I'm trying to get filed values in a nested static class by this simple code:

public static class DataConstants {

    public static class Roles {

        public static readonly Role[] All = new Lazy<Role[]>(LoadAllRoles).Value;

        private static Role[] LoadAllRoles() {
            var fields = typeof(DataConstants.Roles)
                         .GetFields(BindingFlags.Public | BindingFlags.Static);

            foreach (var field in fields) {
                var r = field.GetValue(null);
            }
            return blah-blah;
        }

        public static readonly Role Role1 = new Role {
            Id        = -1,
            Name      = "role1",
        };

        public static Role Role2 = new Role {
            Id        = -2,
            Name      = "role2",
        };

    }

}

Everything seems to be fine and I think this should work. But calling the field.GetValue(null) always returns null. Have you any idea what I missed here? Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire