C# 可以用反射设置静态类的这个静态私有成员吗?
我有一个C# 可以用反射设置静态类的这个静态私有成员吗?,c#,reflection,C#,Reflection,我有一个静态类和静态私有只读成员,该成员是通过类的静态构造函数设置的。下面是一个简化的例子 public static class MyClass { private static readonly string m_myField; static MyClass() { // logic to determine and set m_myField; } public static string MyField {
静态类
和静态私有只读
成员,该成员是通过类的静态构造函数设置的。下面是一个简化的例子
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类获取并设置静态类的值,要么是唯一的选择是重构我被要求进行单元测试的类?下面是一个快速示例,演示如何执行此操作:
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)));
为什么希望实例获取反射信息?只要说typeof(MyClass)
,然后进入反射API的有趣部分…+1,如果答案是这样的话,你就会接受,因为我完全没有意识到类型可以用在Get/SetValue中,而不必是类本身的实例。谢谢,这是否违反了“私有”访问控制?通常任何时候使用反射都是违反了某些法律:)仅供参考-这应该是对原始答案的评论。这是作为答案发布的,并没有直接回答最初的问题,即如何在静态成员上设置值。这是一个很好的信息分享,它只是应该作为一个解释如何解决原始问题的答案的评论