开发者

Action returning void and taking parameter, with ternary operator

开发者 https://www.devze.com 2022-12-11 19:18 出处:网络
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 s

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.

  1. (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) ? ... etc

  2. when 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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号