Question

I know that it was asked for Reflection on ExpandoObjects here before.

My question is a little different. I have static and dynamic functions which should be executed from some function similar to object ExecuteFunction(string name, params object[] parameters).

I execute the static functions via Reflection. So the question is, if I can reuse the MethodInfo call and get a MethodInfo object from the ExpandoObject? Or do I have to implement 2 functions (One with Action and one with MethodInfo)?

Was it helpful?

Solution

You won't get any MethodInfo for the dynamically defined methods on an ExpandoObject.
Dynamically defined methods are the same as dynamically defined properties, they just happen to be of a delegate type.

However, this delegate type contains a property named Method of type MethodInfo which you can utilize:

object ExecuteFunction(IDictionary<string, object> obj, string name,
                       params object[] parameters)
{
    object property;
    if(!obj.TryGetValue(name, out property))
        return null;

    var del = property as Delegate;
    if(del == null)
        return null;

    var methodInfo = del.Method;

    // do with methodInfo what you need to do to invoke it.
    // This should be in its own method so you can call it from both versions of your
    // ExecuteFunction method.
}

Please note that the first parameter is of type IDictionary<string, object>. ExpandoObject implements this interface, and we need no other features from ExpandoObject, so the parameter is just of the type of the implemented interface we need the functionality of.

OTHER TIPS

The opensource framework ImpromptuInterface (available from nuget), provides easy access to the DLR calls that let you call methods by a string name. The only catch is if the method returns void you have to use InvokeMemberAction and if it returns a value you can use InvokeMember. This allows you to invoke methods that are dynamically defined, and calls statically defined methods faster than reflection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top