Created
September 11, 2014 14:34
-
-
Save xanathar/51f5a699645cfa6d120a to your computer and use it in GitHub Desktop.
Get/Set instance property using expression trees dynamic code
This file contains 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
// This builds untyped accessors. Remove converts for strong typing. | |
var paramExp = Expression.Parameter(typeof(object), "obj"); | |
var castParamExp = Expression.Convert(paramExp, this.UserDataDescriptor.Type); | |
var propAccess = Expression.Property(castParamExp, PropertyInfo.Name); | |
var castPropAccess = Expression.Convert(propAccess, typeof(object)); | |
var lambda = Expression.Lambda<Func<object, object>>(castPropAccess, paramExp); | |
Func<object, object> getter = lambda.Compile(); | |
MethodInfo setterMethod = PropertyInfo.GetSetMethod(); | |
var paramExp = Expression.Parameter(typeof(object), "obj"); | |
var paramValExp = Expression.Parameter(typeof(object), "val"); | |
var castParamExp = Expression.Convert(paramExp, this.UserDataDescriptor.Type); | |
var castParamValExp = Expression.Convert(paramValExp, this.PropertyInfo.PropertyType); | |
var callExpression = Expression.Call(castParamExp, setterMethod, castParamValExp); | |
var lambda = Expression.Lambda<Action<object, object>>(callExpression, paramExp, paramValExp); | |
Action<object, object> setter = lambda.Compile(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment