c# - 如何在 .NET Core 中初始化动态类型的静态初始化字段?
问题描述
根据文档,fieldBuilder.SetValue(...)
目前不支持调用。文档建议:
作为一种解决方法,通过反映完成的类型来检索 FieldInfo 并调用 SetValue 来设置字段的值。
这在 .NET Framework 中对于仅静态初始化字段是可能的,但是在 .NET Core 中不再支持。
如何在 .NET Core 中初始化动态类型的静态初始化字段?
编辑(添加示例):
var fb = builder.DefineField("foo", typeof(object), FieldAttributes.Static | FieldAttributes.PrivateScope | FieldAttributes.InitOnly);
// fb.SetValue(...) <-- not supported according to the doc
var c = builder.DefineTypeInitializer().GetILGenerator()
// is it possible to pass myInstance directly to type initializer?
var t = builder.CreateType();
var f = t.GetField("foo", BindingFlags.Static | BindingFlags.NonPublic);
f.SetValue(null, myInstance); // <-- not longer works in .NET Core
解决方案
推荐阅读
- javascript - 使用两个 getElementByIds
- python - 如何在 Python 中使用 evdev 获得绝对触摸板位置?
- assembly - DOSbox 中的 x86 程序集“无法加载程序”
- unit-testing - 在 grails 2.2.3 单元测试中使用多个 mockFor()
- qt - 如何使用 Qt 为我的软件创建帮助文档?
- python - 有什么方法可以将列表中的字符串分配给表格的特定部分?
- python - Python中循环解释的链式比较
- reactjs - useEffect 之外的 Rect 异步调用 - 内存泄漏
- vue.js - vuetity) 如何将图像放入 v-data-table
- ajax - Wordpress AJAX rest api,请求数量后变慢(聊天应用程序)