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

后端 未结 3 739
甜味超标
甜味超标 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

    PrivateType class is analogous to PrivateObject for invoking private static members. Overloaded GetStaticFieldOrProperty methods may be used. http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privatetype(v=VS.100).aspx

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-12 14:34

    The property value can be retreived using reflection. This will require the use of Type.GetField Method (String, BindingFlags) and the FieldInfo.GetValue Method

    string propertyName = "bar";
    FieldInfo fieldInfo = typeof(foo).GetField(propertyName, BindingFlags.NonPublic | BindingFlags.Static);
    object fieldValue = fieldInfo.GetValue(null);
    
    0 讨论(0)
提交回复
热议问题