在对象初始化之前使用反射设置静态变量值?

发布于 2024-08-20 11:44:42 字数 89 浏览 3 评论 0原文

无论如何,是否可以在尚未初始化的对象上设置静态(私有)变量的值? SetValue 方法需要一个实例,但我希望有一种方法可以解决这个问题。

Is there anyway to set the value of a static (private) variable on an object that has not been initialized? The SetValue method requires an instance, but I'm hoping there's a way to get around this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

神妖 2024-08-27 11:44:42

对于静态值,您可以为实例参数传递 null。

var type = typeof(SomeClass);
var field = type.GetField("SomeField", BindingFlags.NonPublic | BindingFlags.Static);
field.SetValue(null, 42);

For static values you can pass null for the instance parameter.

var type = typeof(SomeClass);
var field = type.GetField("SomeField", BindingFlags.NonPublic | BindingFlags.Static);
field.SetValue(null, 42);
装纯掩盖桑 2024-08-27 11:44:42

您可以创建一个公共静态函数并使用它来设置您的私有静态变量吗?

could you create a static function that is public and use it to set your private static variable ?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文