且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 C# 中使用反射更改静态只读字段的值?

更新时间:2023-02-08 14:45:09

如果你想获得一个静态字段,那么你应该使用 BindingFlags.Static 而不是 BindingFlags.Instance代码>,因为后者是例如字段.

If you want to get a static field then you should be using BindingFlags.Static instead of BindingFlags.Instance, as the latter is for instance fields.

然后您可以使用 field.SetValue(null, newValue) 来设置值.请注意,null 可以作为目标参数传递,因为不需要对象实例.假设你有足够的权限,反射会很高兴地改变只读字段的值.

You can then use field.SetValue(null, newValue) to set the value. Note that null may be passed as the target parameter, because no object instance is needed. Assuming you have sufficient privileges, reflection will happily change the value of a readonly field.