Created
November 17, 2020 20:43
-
-
Save zHaytam/d6a7c7fa1c8157feed76536324e5f6db to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static Func<object, object> GenerateGetterLambda(PropertyInfo property) | |
{ | |
// Define our instance parameter, which will be the input of the Func | |
var objParameterExpr = Expression.Parameter(typeof(object), "instance"); | |
// 1. Cast the instance to the correct type | |
var instanceExpr = Expression.TypeAs(objParameterExpr, property.DeclaringType); | |
// 2. Call the getter and retrieve the value of the property | |
var propertyExpr = Expression.Property(instanceExpr, property); | |
// 3. Convert the property's value to object | |
var propertyObjExpr = Expression.Convert(propertyExpr, typeof(object)); | |
// Create a lambda expression of the latest call & compile it | |
return Expression.Lambda<Func<object, object>>(propertyObjExpr, objParameterExpr).Compile(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment