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

后端 未结 2 1540
别跟我提以往
别跟我提以往 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";
    }
    

提交回复
热议问题