为什么三元运算符不是这样工作的
本文关键字:工作 运算符 三元 为什么 | 更新日期: 2023-09-27 18:09:51
为什么不能编译?下面的代码有什么问题?
(_DbContext == null) ? return _DbContext = new ProductAndCategoryEntities() : return _DbContext;
如果我用它是否编译的方式来重新表述:
if (_DbContext == null)
return _DbContext = new ProductAndCategoryEntities();
else return _DbContext;
条件表达式中:
两边的东西是表达式,而不是语句。它们必须求值。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;
更直接一些。返回赋值的值通常看起来有点粗略。
@muratgu的答案是正确的
但是,如果您将变量与null进行比较,那么这样写会更简洁:
return _DbContext ?? new ProductAndCategoryEntities();
它的作用完全相同,而且在我看来更紧凑和可读。
三元运算符如下:
return (_DbContext == null) ? new ProductAndCategoryEntities() : _DbContext;
编辑:在您的示例中,您需要分配_DbContext
,因此您需要第二个语句来执行此操作:
_DbContext = _DbContext ?? new ProductAndCategoryEntities();
return _DbContext;
(感谢@Andrei Zubov提醒我??
操作符)
正如ByteBlast建议的那样,您可以这样做:
if (_DbContext == null)
return (_DbContext = new ProductAndCategoryEntities());
else return _DbContext;
或者,您可以考虑使用"??"操作符。例如:return _DbContext ?? new ProductAndCategoryEntities();
嗯,我发现这段代码很棒,实际上并没有回答我的问题,但我从中学到一些新的东西…如有任何批评,我将不胜感激。
return _DbContext ?? (_DbContext = new ProductAndCategoryEntities());