Skip to content

Instantly share code, notes, and snippets.

@CleanCoder
Last active June 11, 2018 01:30
Show Gist options
  • Save CleanCoder/566ea904d38a54012f2cff6b5d3b19be to your computer and use it in GitHub Desktop.
Save CleanCoder/566ea904d38a54012f2cff6b5d3b19be to your computer and use it in GitHub Desktop.
// Dynamic Invoke Generic Method
MethodInfo methodInfo = typeof(MyClass).GetMethod("TestProc");
MethodInfo genericMethod = methodInfo.MakeGenericMethod(new[] { typeof(string) });
genericMethod.Invoke(null, new[] { "Hello" }); // the first parameter is null, means it is a static method
https://www.codeproject.com/Articles/584720/ExpressionplusbasedplusPropertyplusGettersplusandp
// returns property getter
public static Func<TObject, TProperty> GetPropGetter<TObject, TProperty>(string propertyName)
{
ParameterExpression paramExpression = Expression.Parameter(typeof(TObject), "value");
Expression propertyGetterExpression = Expression.Property(paramExpression, propertyName);
// Convert output type if you want to get object type result
// var objectMember = Expression.Convert(propertyGetterExpression, typeof(object));
Func<TObject, TProperty> result =
Expression.Lambda<Func<TObject, TProperty>>(propertyGetterExpression, paramExpression).Compile();
return result;
}
// returns property setter:
public static Action<TObject, TProperty> GetPropSetter<TObject, TProperty>(string propertyName)
{
ParameterExpression paramExpression = Expression.Parameter(typeof(TObject));
ParameterExpression paramExpression2 = Expression.Parameter(typeof(TProperty), propertyName);
MemberExpression propertyGetterExpression = Expression.Property(paramExpression, propertyName);
Action<TObject, TProperty> result = Expression.Lambda<Action<TObject, TProperty>>
(
Expression.Assign(propertyGetterExpression, paramExpression2), paramExpression, paramExpression2
).Compile();
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment