When I'm trying to use params in an Action delegate...
private Action<string, params object[]> WriteToLogCallBack;
I received this design time error:
Invalid token 'params' in class, struct, or interface member declaration
Any help!
You can pass methods as parameters to a delegate to allow the delegate to point to the method. Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. You can declare a delegate that can appear on its own or even nested inside a class.
By using the params keyword, you can specify a method parameter that takes a variable number of arguments. The parameter type must be a single-dimensional array. No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.
An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type. It can contain minimum 1 and maximum of 16 input parameters and does not contain any output parameter.
You can use the Action<T> delegate to pass a method as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate.
How about this workaround?
private Action<string, object[]> writeToLogCallBack;
public void WriteToLogCallBack(string s, params object[] args)
{
if(writeToLogCallBack!=null)
writeToLogCallBack(s,args);
}
Or you could define your own delegate type:
delegate void LogAction(string s, params object[] args);
Variadic type parameters are not possible in C#.
That's why there're many declarations for Action<...>
, Func<...>
, and Tuple<...>
, for example. It would be an interesting feature, though. C++0x has them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With