jeudi 30 novembre 2017

C# Reflection - Choose Which Overload of a Particular Method to run Based on Number of Parameters

I have a class which has a method with a number of overloads as follows

class MyClass
{
    public bool DoSomething(string linkedServerName, string serverName, string instanceName, string userName, string Password)
    {
        // OverLoad1
        // do stuff
    } 
    public bool DoSomething(string linkedServerName, string serverName, string instanceName)
    {
        // OverLoad2
        // do stuff
    } 
    public bool DoSomething(string linkedServerName, string serverName, string userName, string Password)
    {
        // OverLoad3
        // do stuff
    } 
    public bool DoSomething(string linkedServerName, string serverName)
    {
        // OverLoad4
        // do stuff
    } 
    private bool DoSomething(List<SqlParameter> parms)
    {
        // OverLoad5
        // do stuff
    } 
}

In another class, I have a button click event handler which builds an List of the parameters that should be passed to the above methods, based on user input:

public class MyForm : Form
{
    // code...

    private void Button1_Click(object sernder, EventArgs e)
    {
         List<String> parms = New List<String>();
         //code here which will populate the above list with values dependant on which text boxes the user has filled in

         Type t = new MyClass().GetType();
         Type[] ts = new Type[parms.Count];

         for (int i=0; i< parms.Count; i++)
         {
             ts[i] = typeof(string);
         }

         System.Reflection.MethodInfo m = t.GetMethod("CreateLinkedServer",ts)

         // how do I invoke the method referenced in m??
    }
}

I've got the method I want to invoke which is referenced in the variable m but I'm not sure how to invoke. I know the MethodInfo class has an Invoke method and I've tried:

m.Invoke();
m.Invoke(m, ts);
m.Invoke(this, ts);

and neither of them have worked





Aucun commentaire:

Enregistrer un commentaire