这个问题专门针对 Unity3d IL2CPP 和 iOS。
使用反射调用泛型方法
class SourceValue<T> { public T value; }
class TargetValue<T> { public T value; }
static TargetValue<T> GenericMethod<T> (SourceValue<T> source) {
return new TargetValue<T> { value = source.value };
}
void Main () {
Type genericType = typeof(SourceValue<float>);
Type typeArg = genericType.GenericTypeArguments[0];
MethodInfo mi = GetType ().GetMethod ("GenericMethod", Flags | BindingFlags.Static);
MethodInfo gmi = mi.MakeGenericMethod (typeArg);
object src = new SourceValue<float> { value = 0.5f };
object trg = gmi.Invoke (this, new object[] { src });
}
在 Mac 上的 Unity 编辑器中运行时,这可以按预期工作。在 iOS 上调用失败并出现错误:
ExecutionEngineException: Attempting to call method 'GenericMethod<System.Single>' for which no ahead of time (AOT) code was generated.
at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <00000000000000000000000000000000>:0
仅仅是 AOT 系统不能调用泛型方法还是我遗漏了什么?