【发布时间】:2015-04-10 01:11:43
【问题描述】:
我已阅读有关此问题的帖子,但有人可以为我简化一下吗? 所以我目前正在探索代表,显然有诸如事件之类的用途。 但是,对于简单的操作,例如乘以 2 个数字,首选的是什么? 过度使用代表是不好的做法吗? 以下是我一直在看的内容。
namespace ConsoleApplication32
{
public delegate int Function2(int x, int y);
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Method");
Stopwatch sw2 = Stopwatch.StartNew();
Console.WriteLine("Method: " + Function(5, 5));
sw2.Stop();
Console.WriteLine(sw2.Elapsed);
Console.WriteLine("Delegate");
Stopwatch sw4 = Stopwatch.StartNew();
Function2 g = Function;
Console.WriteLine("Delegate: " + g(5, 5));
sw4.Stop();
Console.WriteLine(sw4.Elapsed);
Console.WriteLine("Anonymous");
Stopwatch sw3 = Stopwatch.StartNew();
Function2 f = delegate(int a, int b) { return a * b; };
Console.WriteLine("Anonymous: " + f(5, 5));
sw3.Stop();
Console.WriteLine(sw3.Elapsed);
Console.WriteLine("Lambda");
Stopwatch sw5 = Stopwatch.StartNew();
Function2 h = (x, y) => { return x * y; };
Console.WriteLine("Lambda: " + h(5, 5));
sw5.Stop();
Console.WriteLine(sw5.Elapsed);
Console.WriteLine("Func Delegate");
Stopwatch sw = Stopwatch.StartNew();
Func<int, int, int> function = (x, y) => x * y;
Console.WriteLine("Func: " + function(5, 5));
sw.Stop();
Console.WriteLine(sw.Elapsed);
}
static int Function(int x, int y)
{
return x * y;
}
}
}
【问题讨论】:
标签: c# methods lambda delegates func