How do I change the value of a static readonly field using reflection in c#?

后端 未结 2 1529
借酒劲吻你
借酒劲吻你 2021-01-12 11:47

The SetFields method in the fieldInfo class takes objects as the first parameter. Is there a way to change the value of the static readonly fields using reflection in C#?

2条回答
  •  时光说笑
    2021-01-12 12:28

    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.

    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.

提交回复
热议问题