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

A.T*_*.T. 2 .net c# logic ternary-operator

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

(_DbContext == null) ? return _DbContext = new ProductAndCategoryEntities() : return _DbContext;
Run Code Online (Sandbox Code Playgroud)

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

 if (_DbContext == null)
                   return _DbContext = new ProductAndCategoryEntities();
               else return _DbContext;
Run Code Online (Sandbox Code Playgroud)

cHa*_*Hao 5

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

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

return (_DbContext == null) ? (_DbContext = new ProductAndCategoryEntities()) : _DbContext;
Run Code Online (Sandbox Code Playgroud)

虽然,在这种情况下,最好是输掉?:并顺其自然if.

if (_DbContext == null) _DbContext = new ProductAndCategoryEntities();
return _DbContext;
Run Code Online (Sandbox Code Playgroud)

这有点直截了当.返回赋值的值通常看起来有点粗略.