locked
Type.InvokeMember w/ Named & Optional Parameters RRS feed

  • Question

  • Is there a way to call the InvokeMember method using named parameters?  It would be great to pass in a list of key/value pairs for the parameter object array argument. 

    Desired:
    Dictionary<object, object> parameters = new Dictionary<object,object>();
    parameters = GetParametersFromDB(CommandName);

    MyClass.GetType().InvokeMember(CommandName, System.Reflection.BindingFlags.InvokeMethod, null, myClass, parameters);

    Existing:
      
    <!--src=[../icons/pubmethod.gif]--><!--src=[../icons/CFW.gif]--><!--src=[../icons/xna.gif]--> InvokeMember(String, BindingFlags, Binder, Object, Object [] ) Invokes the specified member, using the specified binding constraints and matching the specified argument list.


    Scenario:
    I have a database containing a command "aka function alias" and parameter table.  Based on the records in these tables, I'd like to invoke functions, within a C# class, of the same name as the command, with the specified parameter names and values.  C# 4.0 named parameters has potential for a straightforward solution.
    Tuesday, January 5, 2010 5:03 AM

Answers

  • There is no built-in way to do this. Managed assemblies are not guaranteed to have parameter names, they can be omitted from the assembly (e.g. obfuscators do that). If you are lucky and the parameters are in the assembly you want to use (or you force them to stay there), you can use Reflection to implement the desired functionality on your own. However it is not guaranteed to work in general as the parameter names can be gone from some assemblies.

    C# 4.0 named parameters is C# language feature which doesn't have any special support in CLR. It is just syntactic sugar at compile time. What you ask for is however a runtime feature.

    -Karel
    Tuesday, January 5, 2010 5:30 PM
    Moderator