gpt4 book ai didi

c# - 如何使用 CIL 将 POCO 转换为数组?

转载 作者:行者123 更新时间:2023-11-30 22:20:22 26 4
gpt4 key购买 nike

这是我第一次涉足生成的 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);

最佳答案

您可以使用此代码生成已编译的 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,但不是您手动编写它,而是让 LambdaCompile 方法为您完成。

这是一个working demo on ideone .

关于c# - 如何使用 CIL 将 POCO 转换为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15040839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com