我可以用VS2010 PrivateObject访问内部的静态类静态字段? [英] Can i use VS2010 PrivateObject to access a static field inside a static class?

查看:173
本文介绍了我可以用VS2010 PrivateObject访问内部的静态类静态字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能获得进入私人静态字段内的静态类,使用VS2010单元测试类PrivateObject?

让说,我有以下类:

 公共静态类Foo
{
    私人静电棒;
}
 

我可以使用PrivateObject创建副本的,然后得到的字段<? / P>

解决方案

属性值可以使用反射来retreived。这将需要使用 Type.GetField方法(String,的BindingFlags)的和 FieldInfo.GetValue方法

 字符串参数propertyName =酒吧;
字段信息字段信息= typeof运算(富).GetField(propertyName的,BindingFlags.NonPublic可| BindingFlags.Static);
反对fieldValue方法= fieldInfo.GetValue(空);
 

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?

解决方案

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);

这篇关于我可以用VS2010 PrivateObject访问内部的静态类静态字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆