为什么三元运算符不能这样工作?

时间:2013-04-18 05:16:38

标签: c# .net logic ternary-operator

为什么不编译?以下代码有什么问题?

(_DbContext == null) ? return _DbContext = new ProductAndCategoryEntities() : return _DbContext;

如果我按照编译的方式重述它:

 if (_DbContext == null)
                   return _DbContext = new ProductAndCategoryEntities();
               else return _DbContext;

5 个答案:

答案 0 :(得分:5)

条件表达式中:两侧的内容是表达式,而不是语句。他们必须评估一些价值。 return (anything)是一个陈述而不是一个表达式(例如,你不能说x = return _DbContext;),所以它在那里不起作用。

不过,

new ProductAndCategoryEntities()_DbContext似乎都是表达式。因此,您可以将return移动到条件表达式的外部。

return (_DbContext == null) ? (_DbContext = new ProductAndCategoryEntities()) : _DbContext;

虽然在这种情况下,最好丢失?:,然后选择if

if (_DbContext == null) _DbContext = new ProductAndCategoryEntities();
return _DbContext;

这有点简单。返回赋值的值通常看起来有点粗略。

答案 1 :(得分:2)

三元运算符的工作原理如下:

return (_DbContext == null) ? new ProductAndCategoryEntities() : _DbContext;

修改: 在您的情况下,您需要_DbContext分配,因此您需要第二个语句来执行此操作:

_DbContext = _DbContext ?? new ProductAndCategoryEntities();
return _DbContext;

(感谢@Andrei Zubov提醒我??运营商)

答案 2 :(得分:2)

@ muratgu的回答是正确的。

但是,如果将变量与null进行比较,那么写这样的行就更清晰了:

return _DbContext ?? new ProductAndCategoryEntities();

这完全相同,在我看来更紧凑和可读。

答案 3 :(得分:1)

正如 ByteBlast 建议的那样,你可以这样做:

 if (_DbContext == null)
                return (_DbContext = new ProductAndCategoryEntities());
            else return _DbContext;

或者,您可以考虑使用“??”运营商。例如:

return _DbContext ?? new ProductAndCategoryEntities();

答案 4 :(得分:1)

我发现这段代码很棒而且实际上并没有回答我的问题,但我在这里学到了新的东西......任何评论家都会非常感激。

 return _DbContext ?? (_DbContext = new ProductAndCategoryEntities());