首页 > 解决方案 > 如何在 .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

标签: c#reflection.net-corereflection.emit.net-core-3.0

解决方案


推荐阅读