繁体   English   中英

FieldInfo.GetValue() 为嵌套的静态类公共静态字段返回 null

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

我试图通过这个简单的代码在嵌套的静态类中获取归档值:

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",
        };

    }

}

一切似乎都很好,我认为这应该有效。 但是调用field.GetValue(null)总是返回null 你知道我在这里错过了什么吗? 提前致谢。

欢迎来到静态初始化的美妙世界。 静态成员的顺序初始化,他们正在申报,并All在之前声明Role1Role2 因此, Role1Role2不分配,直到之后All分配。

请注意,您在此处使用Lazy<T>毫无意义:您立即调用.Value ,这意味着在All初始化期间调用LoadAllRoles 如果All实际上是一个Lazy<T>或者是里面包裹一个属性Lazy<T>Lazy<T>.Value之后叫做Role1Role2进行初始化,你就不会看到这个问题。

您可以移动的声明Role1Role2给类型的顶部,上面All ,其“修复”的问题。 不过,您最好在静态构造函数中分配All ,因为这不太容易发生意外损坏:

public static class DataConstants {

    public static class Roles {
        public static readonly Role[] All;

        static Roles()
        {
            All = LoadAllRoles();   
        }

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

            foreach (var field in fields) {
                var r = field.GetValue(null);
                Console.WriteLine("field: " + r);
            }

            return new Role[0];
        }

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM