我有一个通用方法,可以尝试使用我自己的 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/