2008-11-11 20 views
13

在.NET中,「out」參數是一件壞事嗎?關於這個話題的任何好文章/討論?在.NET中,「out」參數是一件壞事嗎?

+0

這個問題有一個很好的討論:http://stackoverflow.com/questions/214688/why -does-the-net-framework-guidelines-recommend-that-you-dont-use-refout-argume – Brian 2008-11-11 14:43:18

回答

47

那麼,我有an article on what ref/out do - 但它沒有討論你是否應該使用它們。

基本上out參數通常是一個符號,您希望有效地返回方法的兩個結果。這是通常代碼的氣味 - 但有一些情況下(最顯着與TryXXX模式),你真的想要返回兩條信息的原因很好,它沒有多大意義將它們封裝在一起。

換句話說,避免出/ ref,你可以輕鬆地做到這一點,但不要大量地避開它們。

+1

你的最後一句話是良好的,堅實的,務實的建議。 – 2008-11-11 14:43:38

1

我覺得需要的時候他們是真正有用的。

Msdn article for ref和out參數。

0

好問題。我的回答是我不特別喜歡它們,但是我在其中一個項目中使用它們,其中多個返回值是常見的。我有一個財務數據庫,它返回實際的價格(或空/零),一個主要的錯誤代碼和一個小錯誤代碼。該庫有幾十到幾百種方法,並且每個錯誤代碼都是不同的類型,因此爲每個方法創建自定義類並返回該類的實例將非常不方便。

0

輸出參數,當你需要返回多個對象作爲函數的結果是有用的。我的眼睛,

void doSomeThing(Thing toDoItTo, 
       out OtherThing result1, 
       out AnotherThing result2) 
{ 
    ... 
} 

OtherThing y; 
AnotherThing z; 

doSomeThing(x, out y, out z); 

y.method1(); 
z.method2(); 

struct DoSomeThingResults 
{ 
    public OtherThing Result1; 
    public OtherThing Result2; 
} 

DoSomeThingResults doSomeThing(Thing toDoItTo) 
{ 
    ... 
} 

DoSomethingResults results = doSomeThing(x); 

results.Result1.method1(); 
results.Result2.method2(); 

,另外,採用了參數意味着其結果,保證分配更清潔了很多。

4

在沒有元組的情況下,它們有時是最乾淨的方法。不過,我通常討厭他們。

F#有一些很好的語法糖來處理它們。而不是讓我處理out參數,它將它們視爲返回元組的方法。各種TryParse方法最終返回二元元組:

let success, value = Int32.TryParse("1234") 
(* success is true *) 
(* value is 1234 *) 

這是相當得心應手,並沒有讓我覺得髒。

+0

我也喜歡這個糖! – BuddyJoe 2008-11-11 15:01:37

-1

它不是太壞使用外出

讓我們嘗試precising好處:

using ref force us to initialize it so we are letting the ref variable to place in heap and consume some spaces . 

in most cases we return null if the operation has some none logic conditions 

but with Out we avoid consuming the heap and refspace