2013-04-18 109 views
2

为什么不编译?以下代码有什么错误?为什么三元运算符不是这样工作的?

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

如果我再说一遍而言,如果它编译:

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

'_DbContext =(_DbContext == null)?新的ProductAndCategoryEntities():_DbContext;'这工作? – 2013-04-18 05:21:16

+0

@legendinmaking - 你是完全正确的这是很好的解决方案 – 2013-04-18 05:30:56

+0

它是“条件”运营商btw;它发生在操作数的数量方面* be *三元组... – 2013-04-18 06:23:21

回答

1

以及我发现这个伟大的代码,而不是真正回答我的问题,但我学会在这个新的东西......任何批评将是非常赞赏。

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

为什么不在方法体外执行任务?类似这样的:'_DbContext = GetDbContext();'在你的情况下,你的方法会返回一个_DbContext值并同时改变你的对象的状态,这可能不是一件好事。 – 2013-04-18 05:46:37

+0

它是单例模型....它返回类的单个实例...?运算符检查变量是否为null ..如果它不是null,那么它只是返回实例,否则它将调用右侧表达式,它创建新实例并将其分配给该变量,然后它返回该变量.. – 2013-04-18 05:52:43

+0

啊,我看到。是的,对于单身者来说,这是正确的解决方案。 – 2013-04-18 05:54:34

2

三元操作符的工作原理是这样的:

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

编辑: 在你的情况,你需要_DbContext所以你需要第二个声明:

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

(感谢@Andrei祖博夫提醒我的??运营商)

+0

是的,你是对的......但同时需要_DbContext = new ProductAndCategoryEntities() – 2013-04-18 05:21:42

+1

您是不是指'return(_DbContext == null)? _DbContext = new ProductAndCategoryEntities():_DbContext;'? – Patashu 2013-04-18 05:22:22

+0

@你不能在同一时间完成任务。如果你需要(我相信你会这样做),你需要两条语句,而不是一条。 – muratgu 2013-04-18 05:27:30

2

@ muratgu的答案是正确的。

但是,如果你比较你的变量设置为null,那么它的清洁剂来写一行:

return _DbContext ?? new ProductAndCategoryEntities(); 

这不正是同样的事情,在我看来更紧凑和可读性。

+0

不,它不会完全相同,因为它不会将新实例分配给变量。 – Guffa 2013-04-18 05:31:19

+0

这是指muratgu的答案,其中三元操作的结果是从某种方法返回的。在这种情况下,结果是相同的。 – 2013-04-18 05:33:49

+0

以及很少修改,我发现它的伟大的 return _DbContext? (_DbContext = new ProductAndCategoryEntities()); – 2013-04-18 05:35:35

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; 

这是一个更直接一点。返回任务的价值通常看起来有些粗略。

+0

'他们必须有值。' - >他们必须评估价值?好的答案,否则 – Patashu 2013-04-18 05:28:25

+0

@Patashu:听起来好一点。编辑。 :) – cHao 2013-04-18 05:34:26

1

由于ByteBlast建议,你可以这样来做:

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

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

return _DbContext ?? new ProductAndCategoryEntities(); 
+0

它不会将新对象分配给_DbContext – 2013-04-18 05:37:53

相关问题