Search code examples
c#dynamicreflectionexpandoobjectmethodinfo

MethodInfo from ExpandoObject


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)?


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.