2013-04-18 101 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

相關問題