I am trying to get a MethodInfo object and call Invoke() on it. Here's what I've tried so far:
public class ContactCustomFieldsFacet
{
public Dictionary<string, string> Fields { get; set; } = new Dictionary<string, string>();
}
public static class FacetExtensions
{
public static Func<ContactCustomFieldsFacet, object> Compile(string body)
{
ParameterExpression prm = Expression.Parameter(typeof(ContactCustomFieldsFacet), typeof(ContactCustomFieldsFacet).Name);
LambdaExpression exp = DynamicExpressionParser.ParseLambda(new[] { prm }, typeof(object), body);
return (Func<ContactCustomFieldsFacet, object>)exp.Compile();
}
}
var lambda = FacetExtensions.Compile($"ContactCustomFieldsFacet.Fields[\"test\"]");
var propertyMethod = lambda.Method;
// No control over the below code - it's called by a third party library
ContactCustomFieldsFacet facet = GetFacet();
propertyMethod.Invoke(null, new [] { facet }); // System.ArgumentException: MethodInfo must be a runtime MethodInfo object.
Essentially I want to be able to dynamically create an expression that has the ContactCustomFieldsFacet.Fields
dictionary index field hardcoded for that instance.
I realise I might be on the wrong track so any pointers would be appreciated.
.NET Fiddle: https://dotnetfiddle.net/ecMRye
EDIT
Thanks to Corey I've updated the code but am still getting a similar issue
.NET Fiddle: https://dotnetfiddle.net/5hDOsd
null
object parameter in the invoke? If it actually doesfunc.Method.Invoke(func.Target, ...)
then there's a simple way to do it. Anything that usesDynamicMethod
or similar (including LINQ Expressions and direct emits) will fail on this step.