lundi 1 février 2021

Invoke methods with different number of parameters

I have the following situation and want to implement it as dynamically as possible. Maybe someone has an idea how to solve it.

I have a "main" method which will call methods from other classes by there name. These methods have different signatures. My main method is called with parameters but the other methods can have none, all or only a subset of the origin parameters. Is it possible to invoke the methods with one call and the correct parameters can be assigned?

Solutions I would see are the same signature for every method or an invoke case for every possible parameter combination. But both I don't like. It would be great if there will be something more dynamically.

class Foo {

  public void Start(string name, Type1 param1, Type2 param2, Type3 param3) {
    var method = // getting the method from Bar1, Bar2 or Bar3 by name with reflection

    // Problem is now how to invoke the method with the specified parameters
  }
}

class Bar1 {

  public void Method1(Type1 param1, Type2 param2) {
  }

  public void Method2() {
  }

  public void Method2(Type2 param2) {
  }
}

class Bar2 {

  public void Method3(Type1 param1, Type2 param2, Type3 param3) {
  }

  public void Method4() {
  }
}

class Bar3 {
  
  public void Method5(Type2 param2, Type3 param3) {
  }
}

Thanks for every hint. :)

Edit

In the best case I can do something like this.

method.Invoke(instance, /* all parameters but only the needed will be used */);

This could be a kind of dependency injection. But not sure if this is the right pattern here.





Aucun commentaire:

Enregistrer un commentaire