c# - 在构建到 UWP 和 Il2CPP 之后,通用方法中的 AOT(提前)出现问题

标签 c# unity3d uwp il2cpp

我有一个通用方法,可以尝试使用我自己的 TryGetValue 来通过键从字典中获取通用值,例如(当然,对基本内容进行了很多裁剪)

public class BaseExample
{
    public virtual bool TryGetValue<T>(string key, out T value)
    {
        value = default;
        return false;
    }
}

public class Example : BaseExample
{
    private Dictionary<string, Item> _items = new Dictionary<string, Item>();

    public override bool TryGetValue<T>(string key, out T value)
    {
        value = default;
        if (!GetItem(key, value, out var setting)) { return false; }

        value = (T)setting.Value;
        return true;
    } 

    private bool GetItem<T>(string key, T value, out Item item)
    {
        item = null;

        if (!_items.ContainsKey(key))
        {
            item = null;
            return false;
        }

        item = _items[key];

        return true;
    }
}

这在 Unity 编辑器中有效,但只要它被构建到 UWP 和 IL2CPP,只要我尝试使用例如运行该方法

var value = example.TryGetValue<int>("SomeKey");

它抛出一个

 System.ExecutionEngineException: Attempting to call method 'Example::TryGetValue<System.Int32>' for which no ahead of time (AOT) code was generated.

这可能是什么原因,我该如何解决?

最佳答案

要解决这样的 AOT 问题,您可以强制编译器生成正确的代码。您可以在您的类中添加以下示例方法:

public void UsedOnlyForAOTCodeGeneration() 
{
    // YOUR CODE HERE

    // Include an exception so we can be sure to know if this method is ever called.
    throw new InvalidOperationException(@"This method is used for AOT code generation only. 
    Do not call it at runtime.");
}

关于c# - 在构建到 UWP 和 Il2CPP 之后,通用方法中的 AOT(提前)出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62062589/

相关文章:

c# - 在表中插入数据之前是否可以获取 Id (IDENTITY) 的新值?

C#,事件与委托(delegate)有何不同?

c# - 数组索引超出范围,但应进行定义。编程新手

c# - Unity C# 中嵌套字典的奇怪行为

uwp - UWP中的最小窗口大小

c# - 锯齿状阵列与一个大阵列?

c# - 为什么我的 Windows 窗体按钮上缺少 Aero 视觉样式动画?

c# - 无法播放禁用的音频源(Unity 2d)

c++ - 适用于 Windows (UWP) 而不是 iOS 的通用运行时组件 #ifdef 是什么?

c# - 如何在 UWP 应用程序中生成二维码?