2

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

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

如果我根据它是否编译来重申它:

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

5 回答 5

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;

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

于 2013-04-18T05:25:59.627 回答
2

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

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

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

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

(感谢@Andrei Zubov 提醒我??操作员)

于 2013-04-18T05:19:33.467 回答
2

@muratgu 的回答是正确的。

但是,如果您将变量与 null 进行比较,那么编写如下行会更简洁:

return _DbContext ?? new ProductAndCategoryEntities();

在我看来,这完全一样,并且更紧凑和可读。

于 2013-04-18T05:25:00.493 回答
1

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

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

或者,您可以考虑使用“??” 操作员。例如:

return _DbContext ?? new ProductAndCategoryEntities();
于 2013-04-18T05:33:51.153 回答
1

好吧,我发现这段代码很棒,实际上并没有回答我的问题,但是我从中学到了一些新东西……任何批评者都将不胜感激。

 return _DbContext ?? (_DbContext = new ProductAndCategoryEntities());
于 2013-04-18T05:36:45.320 回答