I have the following method in a C# class
void Mimetodo(string parametro1, string parametro2)
{
// Código del metodo
}
void Mimetodo2(int parametro1)
{
// Código del metodo
}
and now what I want is to match that method to a variable to make a call later, for example something like this:
va = Mimetodo("5", "4");
vb = Mimetodo2(3);
if (opcion == "1") v = vb;
if (opcion == "2") v = va;
v; // Esto seria una llamada a la función que toca.
That is, I want to save the reference to the call of that function.
One option is to use the Action delegate , which allows you to wrap a method.
However, you will still need to pass parameters to the Action instance.
To avoid this, we can use a lambda expression.
Previous note: I had added this answer without realizing that @JhonRM had already provided the correct answer. I was about to delete it when I saw it, but I'm going to leave it because here I also explain a bit about the use of
Func
as opposed toAction
, which I think may be useful to a future user with a similar question. Please do not vote positively, the correct answer was already given by JhonRM and he deserves the positive votes.This is an interesting question. In older versions of the compiler, you could do it using delegates , but the language has long had something that might fit what you're asking for:
Action
yFunc
According to the documentation:
and about
Func
(there are several signatures, this would be a general definition):Combining these delegates with lambdas, it's relatively easy to get what you want. I'll give you an example with both:
Here we define two methods, one with a return value and the other with type
void
. Now we are going to see how we would store a call to each of them, and how we would finally call them:I hope this little explanation has been clear to you.