Action returning void and taking parameter, with ternary operator
I want to write an Action which only takes a PerformanceCounterCategory as a parameter. I know there is Action<>, Func<> and Delegates and there is some distinction between these, but I am not sure what it is. Can someone please tell me what the difference is (I read somewhere that Action does not return, or this may be Func).
I am trying to write something like the following:
Action<PerformanceCounterCategory> action = (int > 5) ? action1 : action2;
action1 and action2 are both methods which return void but take PerformanceCounterCategory as the (only) para开发者_StackOverflow中文版meter.
Is this the right way to go? I keep getting errors about method group/void etc so I am not confident the code above is the best for my needs.
Thanks
You'll need to cast one side or other - or not use the conditional operator.
Basically, ignore the assignment - because the compiler does. It doesn't use the fact that you're trying to assign to a variable to work out the type of the conditional expression. We're left with just:
(i > 5) ? action1 : action2
as the expression. What's the type of that? What delegate type should the method groups be converted to? The compiler has no way of knowing. If you cast one of the operands, the compiler can check that the other can be converted though:
(i > 5) ? (Action<PerformanceCounterCategory>) action1 : action2
Alternatively:
Action<PerformanceCounterCategory> action = action2;
if (i > 5)
{
action = action1;
}
It's unfortunate, but that's life I'm afraid :(
To start by answering your questions about the differences between Action
and Func
An
Action
has a void return.A
Func
returns a value. You specify the type of the return value as the first generic parameter
Func<ReturnType, ParameterType1, ParameterType2...etc>
There are two problems with your code snippet.
(int > 5) doesn't work. int is a data type. You need to create a variable and check it's value.
int myValue = 4;
... (myValue > 5) ? ... etcwhen using the conditional operator (? :) both options must be of the same type. If action1 and action2 are different methods they aren't of the same type, (even if they match the same delegate). The compiler won't be able to figure out which should be converted to which. What you would need to do is cast one to a delegate that matches the other so the compiler can figure out how to convert the two to matching types.
Like this:
Action<PerformanceCounterCategory> action = (int > 5) ? (Action<PerformanceCounterCategory>)action1 : action2;
精彩评论