C# 为什么三元运算符不是这样工作的?

C# 为什么三元运算符不是这样工作的?,c#,.net,logic,ternary-operator,C#,.net,Logic,Ternary Operator,为什么它不编译?以下代码中有什么错误 (_DbContext == null) ? return _DbContext = new ProductAndCategoryEntities() : return _DbContext; 如果我重述它是否编译: if (_DbContext == null) return _DbContext = new ProductAndCategoryEntities(); else ret

为什么它不编译?以下代码中有什么错误

(_DbContext == null) ? return _DbContext = new ProductAndCategoryEntities() : return _DbContext;
如果我重述它是否编译:

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

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

return (_DbContext == null) ? new ProductAndCategoryEntities() : _DbContext;
return _DbContext ?? new ProductAndCategoryEntities();
编辑: 在您的情况下,需要分配
\u DbContext
,因此需要第二条语句:

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

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

@muratgu的回答是正确的

但是,如果将变量与null进行比较,则可以这样编写行:

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

在我看来,它做的事情完全相同,而且更简洁易读。

条件表达式中
两边的东西都是表达式,而不是语句。它们必须评估到一定的价值
return(anything)
是一个语句而不是一个表达式(例如,您不能说
x=return\u DbContext;
),因此它在那里不起作用

新产品和CategoryEntities()
\u DbContext
似乎都是表达式。因此,您可以将
return
移动到条件表达式的外部

return (_DbContext == null) ? (_DbContext = new ProductAndCategoryEntities()) : _DbContext;
不过,在这种情况下,最好不要使用
?:
,而直接使用
if

if (_DbContext == null) _DbContext = new ProductAndCategoryEntities();
return _DbContext;
这更简单一点。返回赋值通常看起来有点粗略。

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

 if (_DbContext == null)
                return (_DbContext = new ProductAndCategoryEntities());
            else return _DbContext;
P>可选地,您可以考虑使用“??”运算符。例如:

return _DbContext ?? new ProductAndCategoryEntities();

嗯,我觉得这段代码很棒,实际上并没有回答我的问题,但我从中学到了一些新的东西。。。任何批评都会受到赞赏

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

\u DbContext=(\u DbContext==null)?新产品和类别实体():\u DbContext这有效吗?@legendinmaking-你完全正确,这是一个很好的解决方案。顺便说一句,这是“有条件”操作符;就操作数而言,它恰好是三元的……是的,您是对的……但同时需要_DbContext=new ProductAndCategoryEntities(),您的意思是
返回(_DbContext==null)_DbContext=new ProductAndCategoryEntities():\u DbContext?@Arun您不能同时执行任务。如果你需要(我相信你需要),你需要两条语句,而不是一条。@muratgu:你可以在表达式中赋值,它不需要是两条语句。这不是一个漂亮的代码,但它确实有效。“它们必须有值。”->它们必须计算为值?回答得好otherwise@Patashu:听起来确实好一点。编辑:)不,它做的事情与它不将新实例分配给变量完全不同。这是muratgu的回答,其中三元运算的结果是从某个方法返回的。在这种情况下,结果是相同的。只要稍加修改,我就会发现它的巨大回报\u DbContext??(_DbContext=newproductandcategoryEntities())@AndreiZubov:是的,它做的事情与muratgu的代码相同,这也有同样的问题。如果_DbContext是一个字段而不是一个内部方法变量,您可以执行赋值。但为什么要从方法返回值,同时将该值赋给字段呢?在我看来,这似乎是一个糟糕的设计决策。您的方法应该只更新对象的状态或返回一些值(请参阅),因为它不会将新对象分配给_dbcontext为什么不在方法体之外进行分配?类似于:“_DbContext=GetDbContext();”在您的例子中,您的方法返回一个_DbContext值,同时更改对象的状态,这可能不是一件很好的事情。它是单例模型…它返回类的单个实例??运算符检查变量是否为null。如果不为null,则只返回实例,否则将调用右侧表达式,创建新实例并将其分配给变量,然后返回该变量。。