Action内的三元运算符不工作

发布于 2024-11-09 03:50:51 字数 273 浏览 4 评论 0原文

有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

黑色毁心梦 2024-11-16 03:50:51

你必须这样做:

var action = new Action<string>(str => Console.WriteLine((str == null) ? "isnull" : "isnotnull"));

You would have to do it like this:

var action = new Action<string>(str => Console.WriteLine((str == null) ? "isnull" : "isnotnull"));
泪之魂 2024-11-16 03:50:51
Action<string> action = new Action<string>( str => 
                    { 
                        if (str == null)
                           Console.WriteLine("isnull");
                        else
                           Console.WriteLine("isnotnull");
                    });
Action<string> action = new Action<string>( str => 
                    { 
                        if (str == null)
                           Console.WriteLine("isnull");
                        else
                           Console.WriteLine("isnotnull");
                    });
你丑哭了我 2024-11-16 03:50:51

我相信三元运算符必须返回一些东西。在您的情况下,它不会返回任何内容,只是执行一条语句。正如 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 :)

半步萧音过轻尘 2024-11-16 03:50:51

问题不在于 lambda,而在于三元运算符中的第二个和第三个表达式必须返回一些内容。 Console.WriteLine 具有 void 返回类型,无法按您的尝试使用。解决方案是将三元运算符放在对 Console.WriteLine 的调用中:

Console.WriteLine(str == null ? "isnull" : "isnotnull")

您可以在 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 has void return type and cannot be used as you are trying to. The solution is to put the ternary operator inside the call to Console.WriteLine:

Console.WriteLine(str == null ? "isnull" : "isnotnull")

You can use this expression in your lambda.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文