C#系统预定义委托类型Action,Func

系统预定义委托类型

1.Action<T>(无返回值)--T为0-16个参数类型

可以指向0-16个参数的方法。

  1.  
    class Program {
  2.  
    static void PrintString()
  3.  
    {
  4.  
    Console.WriteLine( "hello world.");
  5.  
    }
  6.  
    static void PrintInt(int i)
  7.  
    {
  8.  
    Console.WriteLine(i);
  9.  
    }
  10.  
    static void PrintString(string str)
  11.  
    {
  12.  
    Console.WriteLine(str);
  13.  
    }
  14.  
    static void PrintDoubleInt(int i1, int i2)
  15.  
    {
  16.  
    Console.WriteLine(i1+i2);
  17.  
    }
  18.  
    static void Main(string[] args)
  19.  
    {
  20.  
    //Action a = PrintString;//action是系统内置(预定义)的一个委托类型,它可以指向一个没有返回值,没有参数的方法
  21.  
     
  22.  
    //Action<int> a=PrintInt;//定义了一个委托类型,这个类型可以指向一个没有返回值,有一个int参数的方法
  23.  
     
  24.  
    //Action<string> a = PrintString;//定义了一个委托类型,这个类型可以指向一个没有返回值,有一个string参数的方法 在这里系统会自动寻找匹配的方法
  25.  
     
  26.  
    // Action<int, int> a = PrintDoubleInt;
  27.  
    // a(34, 23);
  28.  
     
  29.  
    Console.ReadKey();
  30.  
    //action可以后面通过泛型去指定action指向的方法的多个参数的类型 ,参数的类型跟action后面声明的委托类型是对应着的
  31.  
     
  32.  
    }
  33.  
    }

案例参自:siki老师的课程

2.Func<T1,T2>(有返回值)--T1为0-16个参数类型,T2为返回值类型

可以指向0-16个参数和一个返回值的方法。Func后面必须指定一个返回值类型。先写参数类型,最后一个是返回值类型。

  1.  
    class Program {
  2.  
    static int Test1()
  3.  
    {
  4.  
    return 1;
  5.  
    }
  6.  
    static int Test2(string str)
  7.  
    {
  8.  
    Console.WriteLine(str);
  9.  
    return 100;
  10.  
    }
  11.  
    static int Test3(int i, int j)
  12.  
    {
  13.  
    return i + j;
  14.  
    }
  15.  
    static void Main(string[] args)
  16.  
    {
  17.  
    //Func<int> a = Test1;//func中的泛型类型制定的是 方法的返回值类型
  18.  
    //Console.WriteLine(a());
  19.  
    //Func<string, int> a = Test2;//func后面可以跟很多类型,最后一个类型是返回值类型,前面的类型是参数类型,参数类型必须跟指向的方法的参数类型按照顺序对应
  20.  
    Func< int, int, int> a = Test3;//func后面必须指定一个返回值类型,参数类型可以有0-16个,先写参数类型,最后一个是返回值类型
  21.  
    int res = a(1, 5);
  22.  
    Console.WriteLine(res);
  23.  
    Console.ReadKey();
  24.  
    }
  25.  
    }

案例参自:siki老师的课程

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/qq_33337811/article/details/72822056

猜你喜欢

转载自www.cnblogs.com/Dearmyh/p/9350530.html