Delegate for function with variable parameters

I have such a function

void func(params object[] parameters) { //Function Body } 

It can take the following parameters

 func(10, "hello", 30.0); func(10,20); 

etc.

I wanted to create an Action delegate for the above function. Is it possible? If not, why?

+5
source share
2 answers

You cannot use existing Action delegates with params , but you can declare your own delegate this way:

 public delegate void ParamsAction(params object[] arguments) 

Then:

 // Note that this doesn't have to have params, but it can do public void Foo(object[] args) { // Whatever } ... ParamsAction action = Foo; action("a", 10, 20, "b"); 

Of course, you can create an Action<object[]> for your existing method, but you will lose its params , as it is not declared in Action<T> . For example:

 public static void Foo(params object[] x) { } ... Action<object[]> func = Foo; func("a", 10, 20, "b"); // Invalid func(new object[] { "a", 10, 20, "b" }); // Valid 

So, if you call a delegate from code that wants to use params , you need a delegate type that includes the declaration (according to the first part). If you just want to create a delegate that accepts object[] , then you can create an instance of Action<object[]> using a method that has params in its signature - it's just a modifier, efficient.

+8
source

Here you are faced with the limitations of functional programming in C #: you cannot have a delegate with a variable number of typically typed parameters ( Action delegates have a fixed number of common parameters). But it may be useful for you to create general overloads for each number of parameters:

 void func<T1>(T1 parameter1) { ... } void func<T1,T2>(T1 parameter1, T2 parameter2) { ... } void func<T1,T2,T3>(T1 parameter1, T2 parameter2, T3 parameter3) { ... } 

What you get is the ability to pass these functions as parameters (i.e., pass them simply without using lambda expressions). Therefore, if you have a function like this:

 void anotherFunc(Action<string, int> parameter) { ... } 

Then you can call it like this:

 anotherFunc(func); 
-1
source

Source: https://habr.com/ru/post/1201926/


All Articles