泛型委托 Action、Func

委托在使用的时候有三个步骤: 1、定义委托 2、实例化委托 3、执行委托 每次使用委托,我们都需要定义委托,非常麻烦。

C#已经内置了一些委托给我们使用,无需再重新定义。

一、Action委托 (无返回委托)

1、Action 无参无返回

2、Action 一个参数

3、Action<T1,,,,,,,,,,,,T16> 最多支持16个参数

二、Func委托 (有返回的委托)

1、Func 无参有返

2、Func<T1,Out> 一个参数,有返

3、Func<T1,,,,,,,,,,Out> 最多支持16个参数,有返

 

static void Main(string[] args)
{
    //无参无返调用
    Action action = sayHello;
    action();
    //有参无返调用
    Action<string> action2 = sayHello;
    action2.Invoke("hahah ");

    //有参有返调用
    Func<int,int,int> func = Add;
    Console.WriteLine(func(23, 21));
}

static void sayHello()
{
    Console.WriteLine("你好");
}

static void sayHello(string str) {
    Console.WriteLine(str);
}

static int Add(int a, int b) { 
    return a + b;
}
View Code

 

posted @ 2024-03-19 11:04  行稳致远ac  阅读(45)  评论(0)    收藏  举报