【问题标题】:Method or Delegate or Func [closed]方法或委托或函数[关闭]
【发布时间】: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


    【解决方案1】:

    没有区别。

    delegate(int a, int b) { return a * b; };
    

    (x, y) => { return x * y; };
    

    都将被转换为具有匿名方法的同一个匿名类。所以从效率的角度来看没有区别。但是 lambda 通常更具可读性和更短,因此它们用于 LINQ 语句。将乘法函数包装在 lambda 中并没有什么不好,只是不要创建太多(或者例如不要在循环中创建它们),因为它可能导致实例化大量匿名类。

    【讨论】:

      猜你喜欢
      • 2012-10-20
      • 2015-04-22
      • 2015-07-27
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 2016-01-16
      • 1970-01-01
      • 2013-04-02
      相关资源
      最近更新 更多