是否可以使用反射设置静态类的静态私有成员?

Jam*_*ers 25 c# reflection

我有一个static classstatic private readonly构件的VIA类的设置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.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

由于上面的类是一个静态类,我无法创建它的实例,以便利用传递给FieldInfo.GetValue()调用来检索并稍后设置值m_myField.有没有一种方法我不知道要么使用FieldInfo类来获取和设置静态类的值,还是唯一的选择是重构我被要求进行单元测试的类?

And*_*are 41

这是一个快速示例,说明如何执行此操作:

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";
}
Run Code Online (Sandbox Code Playgroud)

  • 一般来说,只要你使用反射,就违反了某些法律:) (12认同)