You can use this code to generate a compiled lambda expression.
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();
}
This is equivalent to the following manually written code:
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
};
}
This code also produces IL, but instead of you writing it manually, it lets Lambda
's Compile
method do it for your.
Here is a working demo on ideone.