2

这是我第一次涉足生成的 CIL,所以请原谅我的无知。我正在寻找一个简单的 DynamicMethod 可以读取 POCO 的字段,并将它们填充到object[]. 不需要类型转换。我已经把所有我能做的都放在一起了,你能帮忙完成吗?

Type t = typeof(POCO);

DynamicMethod dm = new DynamicMethod("Get" + memberName,typeof(MemberType), new Type[] { objectType }, objectType);
ILGenerator il = dm.GetILGenerator();

// Load the instance of the object (argument 0) onto the stack
il.Emit(OpCodes.Ldarg_0);

// get fields
FieldInfo[] fields = t.GetFields();

// how do I create an array (object[]) at this point?

// per field
foreach (var pi in fields) {

    // Load the value of the object's field (fi) onto the stack
    il.Emit(OpCodes.Ldfld, fi);

    // how do I add it into the array?

}

// how do I push the array onto the stack?

// return the array
il.Emit(OpCodes.Ret);
4

1 回答 1

3

您可以使用此代码生成已编译的 lambda 表达式。

public static Func<T, object[]> MakeFieldGetter<T>() {
    var arg = Expression.Parameter(typeof(T), "arg");
    var body = Expression.NewArrayInit(
        typeof(object)
    ,   typeof(T).GetFields().Select(f => (Expression)Expression.Convert(Expression.Field(arg, f), typeof(object)))
    );
   return (Func<T, object[]>)Expression
        .Lambda(typeof(Func<T, object[]>), body, arg)
        .Compile();
}

这等效于以下手动编写的代码:

object[] GetFields(MyClass arg) {
    return new object[] {
        // The list of fields is generated through reflection
        // at the time of building the lambda. There is no reflection calls
        // inside the working lambda, though: the field list is "baked into"
        // the expression as if it were hard-coded manually.
        (object)arg.Field1
    ,   (object)arg.Field2
    ,   (object)arg.Field3
    };
}

这段代码也会产生 IL,但不是你手动编写它,而是让Lambda'sCompile方法为你做。

这是关于 ideone 的工作演示

于 2013-02-23T13:47:26.267 回答