IL3050:作为本机 AOT 发布时,避免调用使用“RequiresDynamicCodeAttribute”注释的成员

原因

当您将应用程序发布为本机 AOT(通过在项目中将PublishAot 属性设置为 true)时,调用带有 RequiresDynamicCodeAttribute 特性标注的成员可能会在运行时导致异常。 使用此属性标注的成员可能需要能够在运行时动态生成新代码,而 Native AOT 发布模型不提供在运行时生成本机代码的方法。

规则说明

RequiresDynamicCodeAttribute 指示成员引用在运行时可能需要生成代码的代码。

示例

// AOT analysis warning IL3050: Program.<Main>$(String[]): Using member 'System.Type.MakeGenericType(Type[])'
// which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. The native code for
// this instantiation might not be available at runtime.
typeof(Generic<>).MakeGenericType(unknownType);

class Generic<T> { }

struct SomeStruct { }

如何解决冲突

使用属性“RequiresDynamicCodeAttribute”注释的成员获得一条消息,该消息可为作为本地 AOT 发布的用户提供有用的信息。 请考虑根据属性的消息调整现有代码,或者删除有冲突的调用。

在特定模式中调用时,使用 RequiresDynamicCodeAttribute 进行批注的某些 API 不会触发警告。 有关详细信息,请参阅标记为 RequiresDynamicCode 的内部 API