Access private fields

前端 未结 4 1696
无人及你
无人及你 2020-12-06 10:07

Is it possible to get or set private fields?

I want to get System.Guid.c. Is there a way to access it or should I just copy the code from the strut and

4条回答
  •  我在风中等你
    2020-12-06 10:16

    You should try System.Reflection. Here's an example:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Reflection;
    
    namespace AccessPrivateField
    {
        class foo
        {
            public foo(string str)
            {
                this.str = str;
            }
            private string str;
            public string Get()
            {
                return this.str;
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                foo bar = new foo("hello");
                Console.WriteLine(bar.Get());
                typeof(foo).GetField("str", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(bar, "changed");
                Console.WriteLine(bar.Get());
                //output:
                //hello
                //changed
            }
        }
    }
    

提交回复
热议问题