是否有可能设置与反思静态类的这种静态的私有成员? [英] Is it possible to set this static private member of a static class with reflection?
问题描述
我有一个静态类
与静态专用只读
成员即是通过设置类的静态构造函数
。 。下面是一个简单的例子
I have a static class
with static private readonly
member that's set via the class's static constructor
. Below is a simplified example.
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
。有没有办法,我不知道要么获得使用字段信息类来获取和设置一个静态类的值或者是唯一的选择是重构我一直在问的类的单元测试?
Since the above class is a static class, I cannot create an instance of it in order to utilize pass such into a FieldInfo.GetValue()
call to retrieve and later set the value of m_myField
. Is there a way I'm not aware to either get use the FieldInfo class to get and set the value on a static class or is the only option is to refactor the class I've been asked to unit test for?
推荐答案
下面是显示如何做到这一点一个简单的例子:
Here is a quick example showing how to do it:
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";
}
这篇关于是否有可能设置与反思静态类的这种静态的私有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!