如何在Linq表达式中使用Expression.MakeIndex?

Alw*_*wyn 0 .net c# linq expression

属性索引器数组

尝试动态生成以下lambda表达式:

Expression<Func<Program, string>> y = _ => _.x[0];
Run Code Online (Sandbox Code Playgroud)

其中x是列表类型

尝试使用Expression.MakeIndex,但似乎出现了异常:

Expression.MakeIndex(parameter, typeof (Program).GetProperty("x"), new[] {Expression.Constant(0)})
Run Code Online (Sandbox Code Playgroud)

异常消息:

为调用方法'System.Collections.Generic.List`1 [System.String] get_x()提供的参数数量不正确

我该怎么做呢?

Dan*_*rth 5

这里有两个操作:

  1. 获得xparameter
  2. 索引为0的访问项目

您需要为此创建两个单独的表达式:

var property = Expression.Property(parameter, typeof (Program).GetProperty("x"));
var itemAtPosition0 = Expression.MakeIndex(property, typeof(List<string>).GetProperty("Item"),
                     new [] { Expression.Constant(0) });
Run Code Online (Sandbox Code Playgroud)

"Item"引用索引器属性的默认名称。有关此名称以及如何可靠地检测使用的实际名称的更多信息,请查看此答案