Action <t>中的三元运算符无法正常工作</t>

时间:2011-05-20 23:30:50

标签: c# delegates lambda ternary-operator

有一个Action委托,并试图在lambdas中使用其中的三元运算符:

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

给出旧的“唯一分配,减少等允许”错误。

这有可能吗?

4 个答案:

答案 0 :(得分:5)

你必须这样做:

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

答案 1 :(得分:2)

Action<string> action = new Action<string>( str => 
                    { 
                        if (str == null)
                           Console.WriteLine("isnull");
                        else
                           Console.WriteLine("isnotnull");
                    });

答案 2 :(得分:1)

我相信三元运算符必须返回一些东西。在你的情况下,它不返回任何东西,只是执行一个语句。正如Reddog所说,你必须把你的三元组放在Console.WriteLine调用中,这实际上是代码更少:)

答案 3 :(得分:0)

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

的调用中
Console.WriteLine(str == null ? "isnull" : "isnotnull")

您可以在lambda中使用此表达式。

相关问题