1. 程式人生 > >System.Action的使用(lambda 表達式)

System.Action的使用(lambda 表達式)

[] str2 class internal sys private tr1 string sta

對於Action的使用方法使用如下:

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string first = "First";
            var action = new Action(() => { Console.WriteLine(first); });
            action();

            var action2 = new Action<string
>((s) => { Console.WriteLine($"Action<T>:{s}"); }); action2(first); var action3 = new Action<string, string>((s1, s2) => { Console.WriteLine($"Action<T1,T2>:{s1},{s2}"); }); action3(first, "second"); } } }

使用dotPeek通過反編譯,得到代碼:

namespace ConsoleApp1
{
  internal class Program
  {
    private static void Main(string[] args)
    {
      string first = "First";
      ((Action) (() => Console.WriteLine(first)))();
      ((Action<string>) (s => Console.WriteLine(string.Format("Action<T>:{0}
", (object) s))))(first); ((Action<string, string>) ((s1, s2) => Console.WriteLine(string.Format("Action<T1,T2>:{0},{1}", (object) s1, (object) s2))))(first, "second"); } } }

下面寫一種與反編譯出來的相似的方法

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string first = "First";
            var action = new Action(() => { Console.WriteLine(first); });
            action();

            var action2 = new Action<string>((s) => { Console.WriteLine($"Action<T>:{s}"); });
            action2(first);

            var action3 = new Action<string, string>((s1, s2) =>
            {
                Console.WriteLine($"Action<T1,T2>:{s1},{s2}");
            });
            action3(first, "second");

            new Action(() => { Console.WriteLine(first); })();
            new Action<string>((s) => { Console.WriteLine($"Action<T>:{s}"); })(first);
            new Action<string, string>((s1, s2) =>
            {
                Console.WriteLine($"Action<T1,T2>:{s1},{s2}");
            })(first, "second");
        }
    }
}

看一下反編譯的結果:

namespace ConsoleApp1
{
  internal class Program
  {
    private static void Main(string[] args)
    {
      string first = "First";
      ((Action) (() => Console.WriteLine(first)))();
      ((Action<string>) (s => Console.WriteLine(string.Format("Action<T>:{0}", (object) s))))(first);
      ((Action<string, string>) ((s1, s2) => Console.WriteLine(string.Format("Action<T1,T2>:{0},{1}", (object) s1, (object) s2))))(first, "second");
      ((Action) (() => Console.WriteLine(first)))();
      string str1 = first;
      ((Action<string>) (s => Console.WriteLine(string.Format("Action<T>:{0}", (object) s))))(str1);
      string str2 = first;
      string str3 = "second";
      ((Action<string, string>) ((s1, s2) => Console.WriteLine(string.Format("Action<T1,T2>:{0},{1}", (object) s1, (object) s2))))(str2, str3);
    }
  }
}

反編譯結果是幫我們定義了幾個變量。

System.Action的使用(lambda 表達式)