如何在 C# 中使用反射更改静态只读字段的值? [英] How do I change the value of a static readonly field using reflection in c#?

查看:98
本文介绍了如何在 C# 中使用反射更改静态只读字段的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

fieldInfo 类中的 SetFields 方法将对象作为第一个参数.有没有办法在 C# 中使用反射来更改静态只读字段的值?

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#?

到目前为止我有

var field = typeof(ClassName).GetField("FieldName",BindingFlags.Instance|BindingFlags.NonPublic);

推荐答案

如果你想获得一个静态字段,那么你应该使用 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.

这篇关于如何在 C# 中使用反射更改静态只读字段的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆