.Net lambda expression— where did this parameter come from?

前端 未结 5 763
南旧
南旧 2020-12-06 09:50

I\'m a lambda newbie, so if I\'m missing vital information in my description please tell me. I\'ll keep the example as simple as possible.

I\'m going over someone

5条回答
  •  日久生厌
    2020-12-06 10:37

    p is just a dummy name, it's the name of the parameter like in any method. You could name it x or Fred, if you like.

    Remember, lambda expressions are just very, very special anonymous methods.

    In regular methods you have parameters, and they have names:

    public double GetQuantitysaved(ViewModelBase p) {
        return QuantitySaved;
    }
    

    In anonymous methods you have parameters, and they have names:

    delegate(ViewModelBase p) { return QuantitySaved; }
    

    In lambda expressions you have parameters, and they have names:

    p => QuantitySaved
    

    The p here plays the same role in all three versions. You can name it whatever you want. It's just the name of a parameter to the method.

    In the last case, the compiler does a lot of work to figure out that p represents a parameter of type ViewModelBase so that p => QuantitySaved can play the role of

    Expression> property
    

    For fun I changed the code from p to this, since SampleViewModel inherits from ViewModelBase, but I was met with a series of compiler errors, the first one of which stated Invalid expression term '=>' This confused me a bit since I thought that would work.

    Well, this is not a valid parameter name because it's a reserved keyword. It's best to think of p => QuantitySaved as

    delegate(ViewModelBase p) { return QuantitySaved; }
    

    until you get comfortable with the idea. In this case, this could never be substituted in for p as it is not a valid parameter name.

提交回复
热议问题