我正在尝试通过在运行时发出 IL 来编译 DynamicMethod。我希望它执行以下操作:
array.OrderByDesc( /* Select Field/Property Expression*/ ).ToArray();
编译 DynamicMethod 的方法有一个FieldInfo变量,我想将它用于OrderByDesc需要的表达式。
这是我到目前为止所拥有的:
public static FilterDelegate<T> CreateDelegate<T>( Expression<Func<T, double>> expression )
{
var field = expression.GetFieldInfo();// Extension, gets FieldInfo from expression
...
il.Emit( OpCodes.Ldloc_1 ); // Loads an array (T[])
il.Emit( OpCodes.Call, typeof( Enumerable ).GetMethod( nameof( Enumerable.OrderByDescending ), new Type[0]).MakeGenericMethod( typeof( T ) ) );
il.Emit( OpCodes.Call, typeof( Enumerable ).GetMethod( nameof( Enumerable.ToArray ) ).MakeGenericMethod( typeof( T ) ) );
il.Emit( OpCodes.Stloc_1 ); // Stores the sorted array
}
需要注意的几点:
提供的表达式是一个选择器,它指定在整个编译方法中使用哪个字段(或属性支持值)。
这个方法不仅仅是调用OrderByDescending(),还包含很多低级优化。排除排序,预计在大多数情况下运行时间低于 40ns。
如何将表达式传递给编译方法或FieldInfo正确调用OrderByDescending()?
吃鸡游戏
隔江千里
随时随地看视频慕课网APP
相关分类