开发者

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

开发者 https://www.devze.com 2023-02-15 15:53 出处:网络
Is it possible to get access to a private static field inside a static class, using the VS2010 Unit开发者_如何学运维 Test class PrivateObject ?

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:

public static class foo
{
    private static bar;
}

Can i use PrivateObject to create a copy of foo, and then get the bar field?


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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号