Action内的三元运算符不工作
有一个 Action 委托并尝试将其中的三元运算符与 lambda 一起使用:
Action<string> action = new Action<string>( str => (str == null) ?
Console.WriteLine("isnull") : Console.WriteLine("isnotnull")
给出旧的“仅允许赋值、递减等”错误。
这有可能吗?
Have an Action delegate and trying to use the ternary operator inside of it with lambdas:
Action<string> action = new Action<string>( str => (str == null) ?
Console.WriteLine("isnull") : Console.WriteLine("isnotnull")
Gives the old "only assignment, decrement, etc. allowed" error.
Is this possible somehow?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你必须这样做:
You would have to do it like this:
我相信三元运算符必须返回一些东西。在您的情况下,它不会返回任何内容,只是执行一条语句。正如 Reddog 所说,您必须将三元数放入 Console.WriteLine 调用中,这实际上是更少的代码:)
I believe the ternary operator has to return something. In your case it's not returning anything, just executing a statement. As Reddog said, you have to put your ternary inside the Console.WriteLine call, which is actually less code :)
问题不在于 lambda,而在于三元运算符中的第二个和第三个表达式必须返回一些内容。
Console.WriteLine
具有void
返回类型,无法按您的尝试使用。解决方案是将三元运算符放在对Console.WriteLine
的调用中:您可以在 lambda 中使用此表达式。
The problem is not the lambda but the fact that the second and third expression in the ternary operator has to return something.
Console.WriteLine
hasvoid
return type and cannot be used as you are trying to. The solution is to put the ternary operator inside the call toConsole.WriteLine
:You can use this expression in your lambda.