When two numbers are added, subtracted, multiplication, and division, one solution is implemented by delegation. As follows:
class Program
{
private delegate int CaculateDel(int num1, int num2);
static void Main(string[] args)
{
CaculateDel caculateDel = Add;
Console.WriteLine(caculateDel.Invoke(1,2).ToString());
Console.ReadKey();
}
static int Add(int num1, int num2)
{
return num1 + num2;
}
}
Above, the add method is assigned to the delegate variable of caculatedel type.
If you use the anonymous method, it is:
class Program
{
private delegate int CaculateDel(int num1, int num2);
static void Main(string[] args)
{
CaculateDel caculateDel = delegate(int num1, int num2)
{
return num1 + num2;
};
Console.WriteLine(caculateDel.Invoke(1,2).ToString());
Console.ReadKey();
}
}
It can be seen that the anonymous method is the delegate, and the anonymous method has better flexibility, so you do not need to write the method "dead" in advance ".
If we use system. the stopwatch instance method reset, start, and stop of diagnostics can be used to reset, start, and end stopwatch. The elapsedtickes attribute of stopwatch is used to display the time. We can find that the anonymous method is more efficient.