我在iPod上,所以目前不能给出完整的例子:但是:
-
声明object[]类型的参数(
Expression.Param(typeof(object[]))
)并将其存储在变量中
-
索引器
获取索引器的表达式,并且“
Convert
或“演员”(又是iPod!)投球
-
使用
Expression.Invoke
,传递内部表达式和上面生成的indexer+cast
如果你需要的话,我很乐意稍后再做一个完整的例子(当我在PC机上时)
Type[] types = new Type[] { typeof(int), typeof(float), typeof(string) };
var constructorInfo = typeof(SomeType).GetConstructor(types);
var parameters = types.Select((t,i) => Expression.Parameter(t, "p" + i)).ToArray();
var someType1Exp = Expression.New(constructorInfo, parameters);
var inner = Expression.Lambda(someType1Exp, parameters);
var args = Expression.Parameter(typeof(object[]), "args");
var body = Expression.Invoke(inner,
parameters.Select((p,i) => Expression.Convert(Expression.ArrayIndex(args, Expression.Constant(i)), p.Type)).ToArray());
var outer = Expression.Lambda<Func<object[], object>>(body, args);
var func = outer.Compile();
object[] values = {1, 123.45F, "abc"};
object obj = func(values);
Console.WriteLine(obj);
或者作为一个表达式:
Type[] types = new Type[] { typeof(int), typeof(float), typeof(string) };
var constructorInfo = typeof(SomeType).GetConstructor(types);
var args = Expression.Parameter(typeof(object[]), "args");
var body = Expression.New(constructorInfo,
types.Select((t,i) => Expression.Convert(Expression.ArrayIndex(args, Expression.Constant(i)), t)).ToArray());
var outer = Expression.Lambda<Func<object[], object>>(body, args);
var func = outer.Compile();
object[] values = {1, 123.45F, "abc"};
object obj = func(values);
Console.WriteLine(obj);