Answer the question
In order to leave comments, you need to log in
C# - the method takes another method as a parameter, how to understand?
I'm studying unit tests and found a gap in my basic C# knowledge.
Here is the method
mock.Setup( m => m.ApplyDiscount(It.IsAny()) )
.Returns(total => total);
In this case, Setup takes a lambda expression m => m.ApplyDiscount(It.IsAny()) can anyone explain how to understand this? Give the name of the topic that I need to learn in order to understand such expressions.
Do I guess correctly that Setup is not a method but a delegate?
Answer the question
In order to leave comments, you need to log in
Setup
is the usual method.
Do Returns
not pay attention, it is also a regular method, it is by itself, it's just Fluid, delegates and lambdas have nothing to do with it.
But what is written in the form of a lambda expression is a delegate.
I wrote an example here with four similar syntaxes that differ in appearance, but are essentially equivalent, if you reproduce it (create a WinForms application, a form and a button with a handler), you will understand what it is and approximately why it can be used:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public delegate void EventHandler2(
int i
);
public Form1()
{
InitializeComponent();
}
void setEventHandler(EventHandler2 eh)
{
eh.Invoke(123);
}
private void button1_Click(object sender, EventArgs e)
{
//Example 1
setEventHandler(x => MessageBox.Show(x.ToString()));
//Example 2 (equalent)
setEventHandler((x) => { MessageBox.Show(x.ToString()); });
//Example 3 (equalent)
setEventHandler(delegate(int x) { MessageBox.Show(x.ToString()); });
//Example 4 (equalent)
setEventHandler(goodbyeDelegatesAndLambdas);
}
void goodbyeDelegatesAndLambdas(int x)
{
MessageBox.Show(x.ToString());
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question