Is it possible to set this static private member of a static class with reflection?

后端 未结 2 1524
别跟我提以往
别跟我提以往 2021-02-05 01:52

I have a static class with static private readonly member that\'s set via the class\'s static constructor. Below is a simplified example.

相关标签:
2条回答
  • 2021-02-05 02:36

    Here is a quick example showing how to do it:

    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";
    }
    
    0 讨论(0)
  • 2021-02-05 02:54

    This "null rule" also applies to FieldInfo.GetValue() for a static field, e.g.,

    Console.Writeline((string)(field.GetValue(null)));
    
    0 讨论(0)
提交回复
热议问题