2015-10-09 62 views
-5

什麼可以成爲理由的代碼拉姆達函數的行爲古怪

Line ScoreLine; 
ScoreLine = Charting.CreateLine(
     "Score", "", Symbol, new Pen(Color.Pink), 
     LineStyle.Line, Charting.PriceChart, 2 
); 

導致不同的行爲比

Line ScoreLine; 
Func<string, Color, int, Line> createLine 
= (string label, Color color, int pad) 
=> Charting.CreateLine(label, "", Symbol, new Pen(color), 
         LineStyle.Line, Charting.PriceChart, pad); 
ScoreLine = createLine("Score", Color.Pink, 2); 

它看起來像一個微不足道的重構,但第二個版本中的行爲很奇怪的態度。看起來lambda函數的參數並不重要,並且事先設置爲特定值。

+0

哪些參數?你已經硬編碼並關閉的那些將繼續烘焙到'Func'中,其他的可以通過將不同的值傳遞給'Func'來修改。如果你能想出一個證明另有說明的[SSCCE](http://sscce.org/),那麼這對診斷問題會非常有幫助。 –

+0

你能描述一下發生了什麼好一點嗎?哪些值似乎被使用?他們從哪裏來? – 31eee384

+0

我無法輕鬆製作SSCCE,因爲它是一個GUI應用程序,結果只在GUI中可見。 會發生什麼情況是第二個版本不會繪製粉紅線,而是繪製紅線。以前版本的應用中,Red用於同一行。 – aickley

回答

0

有一件事我不知道這些圖表的東西是什麼,你的Func<string, Color, int, Line>表示它返回Line,但你使用lambda時將方法調用的結果分配給ScoreLine。在您的非lambda示例中,您將結果分配給Line。這可能是一個問題嗎?你不是在說什麼ScoreLineLine的類型,所以我不能確定。

+0

對不起,這是一個錯字。 'ScoreLine'屬於'Line'類型,在這兩種情況下,賦值都是爲了'ScoreLine'。 – aickley

1

測試代碼:

Func<string, Color, int, string> createLine 
    = (label, color, pad) 
    => ("Label: " + label + " | pad: " + pad + " | Color: " + color.ToString()); 

Console.WriteLine(createLine("Test 1", Color.Red, 1)); 
Console.WriteLine(createLine("Test 2", Color.Green, 2)); 
Console.WriteLine(createLine("Test 3", Color.Blue, 3)); 

,你應該看到這一點:

> Label: Test 1 | pad: 1 | Color: Color [Red] 
> Label: Test 2 | pad: 2 | Color: Color [Green] 
> Label: Test 3 | pad: 3 | Color: Color [Blue] 

我覺得克里斯騎士是正確的,你的問題是您在返回值分配給不同的類比Line還有一些其他代碼會改變你的顏色。

+0

謝謝。我在'Line'的整個生命週期中檢查了'ScoreLine.Color'是否是'Pink'。這種情況意味着線路屬性被GUI應用覆蓋。 – aickley