Can i use VS2010 PrivateObject to access a static field inside a static class?

后端 未结 3 731
甜味超标
甜味超标 2021-02-12 13:50

Is it possible to get access to a private static field inside a static class, using the VS2010 Unit Test class PrivateObject ?

Let say i have the following class:

<
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-12 14:32

    The answer by Deepun can be very useful. I wanted to add a specific example to help people who come this way.

    Class with private static member.

    public class foo
    {
       private static int bar;
    }
    

    Code to get value.

    PrivateType pt = new PrivateType(typeof(foo));
    int bar = (int)pt.GetStaticFieldOrProperty("bar");
    

    Code to change value

    PrivateType pt = new PrivateType(typeof(foo));
    pt.SetStaticFieldOrProperty("bar", 10);
    

    This will work regardless of the class being static or not.

提交回复
热议问题