c#中的Lambda函数行为怪异

本文关键字:函数 中的 Lambda | 更新日期: 2023-09-27 18:16:53

为什么代码

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函数的参数似乎并不重要,而是先验地设置为特定的值。

c#中的Lambda函数行为怪异

测试代码:

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]

我认为Chris Knight是对的,你的问题是你将你的返回值分配给一个不同于Line的类,并且会有一些其他代码改变你的颜色。

我看到的一件事,而不知道这些图表的东西是什么,你的Func<string, Color, int, Line>说它返回一个Line,但是你在使用lambda时将方法调用的结果分配给ScoreLine。在非lambda示例中,将结果分配给Line。这会是个问题吗?你没有说ScoreLineLine的类型是什么,所以我不能确定。