是否可以使用reflection设置静态类的静态私有成员?
我有一个带有static private readonly
成员的static class
,它通过类的static constructor
。 下面是一个简化的例子。
public static class MyClass { private static readonly string m_myField; static MyClass() { // logic to determine and set m_myField; } public static string MyField { get { // More logic to validate m_myField and then return it. } } }
由于上面的类是一个静态类,我无法创建它的实例,以便将这样的传递用于FieldInfo.GetValue()
调用以检索并稍后设置m_myField
的值。 有没有一种方法我不知道要么使用FieldInfo类来获取和设置静态类的值,还是唯一的选择是重构我被要求进行unit testing的类?
这是一个快速示例,说明如何执行此操作:
using System; using System.Reflection; class Example { static void Main() { var field = typeof(Foo).GetField("bar", BindingFlags.Static | BindingFlags.NonPublic); // Normally the first argument to "SetValue" is the instance // of the type but since we are mutating a static field we pass "null" field.SetValue(null, "baz"); } } static class Foo { static readonly String bar = "bar"; }
这个“空规则”也适用于静态字段的FieldInfo.GetValue(),例如,
Console.Writeline((string)(field.GetValue(null)));
- ASP标识表列更改,但新列名称无法进行映射
- NSubstitute vs PRISM EventAggregator:断言调用方法会触发具有正确有效负载的事件
- 无法运行使用Microsoft Fakes的unit testing – ShimsContext.Create()方法中的exception
- ASP.NET MVC 2自定义ModelValidator的问题
- Google API / OAUTH / NativeApplicationClient / OAuth2Authenticator>退出?
- 有没有更好的方法在C#中自定义SOAP头?
- 枚举Int32类型的成员
- miscfunction的静态类的理想类名
- 将DateTime转换为UTC时,调整规则是什么?