Nat*_*gge 5 c# json.net unity-game-engine
我已经在项目中多次使用 Json.Net 来保存数据,并且从不担心为序列化类创建无参数构造函数。
\n现在我正在做一个适合这种情况的项目。它使用 Json.Net 序列化一些没有无参数构造函数的类,并且工作正常。然而,一位同事警告我,我很幸运从未遇到过任何问题,并且错误ExecutionEngineException: Attempting to JIT compile method
\xc2\xa0 可能会在 iOS 构建中随时出现并导致我的应用程序崩溃。
我看过很多有关 Json.Net 和构造函数或 Json.Net 和 AOT 的主题,但没有看到有关 Json.Net、构造函数和 AOT 的主题。至少本世纪没有任何事情。
\n所以,我的问题是,我是否应该担心 iOS 设备中没有无参数构造函数的序列化类?
\n编辑:我的类有构造函数,但它们接收参数。我想知道除了它们之外我是否还需要不带参数的构造函数。
\n正如评论中提到的,您应该担心的是字节码剥离,而不是有关默认构造函数数量的任何事实。
Newtonsoft.Json 实例化类型的反射部分是不可避免的,因此为了保护所有类免遭字节码剥离,您有几个选择。
1:通过link.xml
文件禁用字节码剥离。例子:
<linker>
<assembly fullname="MyAssembly">
<type fullname="MyAssembly.MyCSharpClass" />
</assembly>
</linker>
Run Code Online (Sandbox Code Playgroud)
我发现Unity的官方文档分散且缺乏,所以我重写了一些文档。阅读有关如何使用该link.xml
文件的更多信息: https: //github.com/jilleJr/Newtonsoft.Json-for-Unity/wiki/Fix-AOT-using-link.xml
^基于对 UnityLinker 和现有文档的行为进行逆向工程。如需进一步阅读,请访问:
选项 2:通过属性禁用字节码剥离Preserve
。
将属性添加到类、方法、字段、属性、事件或程序集中将保证它不会被 UnityLinker 删除。该属性必须被命名PreserveAttribute
,因此使用UnityEngine.Scripting.PreserveAttribute
或您自己调用的属性PreserveAttribute
将产生相同的结果。
using UnityEngine.Scripting;
[Preserve]
public class YourTypeWithSpecialConstructor
{
public YourTypeWithSpecialConstructor(int value1, string value2)
{
}
}
Run Code Online (Sandbox Code Playgroud)
阅读有关属性用法的更多信息Preserve
:https://docs.unity3d.com/ScriptReference/Scripting.PreserveAttribute.html(这个我还没有重写:p)
选项 3:使用我发布的 Newtonsoft.Json for Unity 中的 AotHelper。
Assets Store 上的 JSON .NET for Unity 包基于 Newtonsoft.Json 8.0.3,但在撰写本文时,我的包目前已更新为 Newtonsoft.Json 12.0.3,并通过 Unity Package Manager 交付给更轻松地保持最新状态: https://github.com/jilleJr/Newtonsoft.Json-for-Unity#readme
它包括Newtonsoft.Json.Utilities。AotHelper类,它不仅禁用字节码剥离,还强制编译某些类型,这对于泛型来说非常有用。用法示例:
using Newtonsoft.Json.Utilities;
using UnityEngine;
public class AotTypeEnforcer : MonoBehaviour
{
public void Awake()
{
AotHelper.Ensure(() => {
_ = new YourGenericTypeWithSpecialConstructor<int>(0, null);
_ = new YourGenericTypeWithSpecialConstructor<float>(0, null);
_ = new YourGenericTypeWithSpecialConstructor<string>(null, null);
_ = new YourGenericTypeWithSpecialConstructor<bool>(true, null);
});
}
}
public class YourGenericTypeWithSpecialConstructor<T>
{
public YourGenericTypeWithSpecialConstructor(T value1, string value2)
{
}
}
Run Code Online (Sandbox Code Playgroud)
在这里阅读有关如何使用 AotHelper 的更多信息: https: //github.com/jilleJr/Newtonsoft.Json-for-Unity/wiki/Fix-AOT-using-AotHelper
归档时间: |
|
查看次数: |
1096 次 |
最近记录: |