簡體   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