代码之家  ›  专栏  ›  技术社区  ›  JamesEggers

可以用反射设置静态类的这个静态私有成员吗?

  •  24
  • JamesEggers  · 技术社区  · 16 年前

    static class 具有 static private readonly 通过类的 static constructor . 下面是一个简化的例子。

    public static class MyClass
    {
        private static readonly string m_myField;
    
        static MyClass()
        {
            // logic to determine and set m_myField;
        }
    
        public static string MyField
        {
            get
            {
                // More logic to validate m_myField and then return it.
            }
        }
    }
    

    因为上面的类是一个静态类,所以我无法创建它的实例来将这样的传递应用到 FieldInfo.GetValue() 调用以检索并稍后设置 m_myField . 是否有一种方法我不知道,要么使用FieldInfo类获取并设置静态类的值,要么是唯一的选择是重构我被要求进行单元测试的类?

    2 回复  |  直到 16 年前
        1
  •  50
  •   Andrew Hare    16 年前

    下面是一个快速示例,演示如何执行此操作:

    using System;
    using System.Reflection;
    
    class Example
    {
        static void Main()
        {
            var field = typeof(Foo).GetField("bar", 
                                BindingFlags.Static | 
                                BindingFlags.NonPublic);
    
            // Normally the first argument to "SetValue" is the instance
            // of the type but since we are mutating a static field we pass "null"
            field.SetValue(null, "baz");
        }
    }
    
    static class Foo
    {
        static readonly String bar = "bar";
    }
    
        2
  •  0
  •   Rowan Smith    12 年前

    此“空规则”也适用于静态字段的FieldInfo.GetValue(),例如。,

    Console.Writeline((string)(field.GetValue(null)));