Search code examples
c#reflectionclearscript

How to invoke method of dynamic object using reflection


I've got dynamic object which contains some execute function generated by V8ScriptEngine. I need to execute this method with parameters which was specified in Dictionary object. I tried this approach:

private dynamic InvokeMethod(dynamic scriptObject, Dictionary<string, string> inpuValues)
{
        dynamic result;
        ((DynamicObject) scriptObject).TryInvoke(scriptObject.execute, inpuValues.Values.ToArray(), out result);
        return result;
}

but it throws

TypeError: Method or property not found

I also tried scriptObject.GetType().GetMethod("execute").Invoke with the same result But if i try to execute it manually (e.g scriptObject.execute(1,2)) it will return valid result. How can i invoke this method dynamically?


Solution

  • How about going through IReflect?

    var result = ((IReflect)scriptObject).InvokeMember(
        "execute",
        BindingFlags.InvokeMethod, null, null,
        inpuValues.Values.Cast<object>().ToArray(),
        null, null, null);