在Monotouch中编译lambdas并在设备上调用委托

Lou*_*oux 9 c# lambda delegates expression-trees xamarin.ios

我目前正在MonoTouch中移植一个.NET代码库,我正在研究一种接收一个的方法Expression<T>.我正在尝试编译它,然后动态调用它.

这是我做的:

// Here's an example of what I could receive
Expression<Action<int>> expression = (a => Console.WriteLine (a * 2));

// And here's what I'm trying to do to invoke it
expression.Compile().DynamicInvoke(6);
Run Code Online (Sandbox Code Playgroud)

这在iOS模拟器中工作正常,结果"12"在我的控制台中打印.但后来我在iPad上试了一下,我收到了以下异常.

Object reference not set to an instance of an object
   at System.Linq.jvm.Runner.CreateDelegate ()
   at System.Linq.Expressions.LambdaExpression.Compile ()
   at System.Linq.Expressions.Expression`1[System.Action`1[System.Int32]].Compile ()
   at TestSolution2.AppDelegate.FinishedLaunching (MonoTouch.UIKit.UIApplication app, MonoTouch.Foundation.NSDictionary options)
Run Code Online (Sandbox Code Playgroud)

我做错了什么,我怎么能让它发挥作用?

The*_*man 11

不熟悉System.Linq.Expressions,但可能它涉及运行时代码生成.

iOS中没有JIT,所有代码都必须提前编译.同样的限制不适用于模拟器,因此您的代码在那里运行.

看到这里.

Compile()iOS设备不支持该方法,因为该设备阻止JIT引擎运行.编译本身是使用System.Reflection.Emit实现的,而这又需要一个正常运行的JIT.所以上面的代码永远不会使用表达式树.