C# 中的 Func 代理 和 Action代理(二)

Action 也是定义在System命名空间下的一个delegate类型,Action代理 与 Func代理 除了<>里的所有类型都为参数类型以外没有别的区别 

注意:Action是不包含返回值的

如果不用Action 代理,自定义代理如下:

public delegate void Print(int val);

static void ConsolePrint(int i)
{
    Console.WriteLine(i);
}

static void Main(string[] args)
{           
    Print prnt = ConsolePrint;
    prnt(10);
}

使用Action代理:

static void ConsolePrint(int i)
{
    Console.WriteLine(i);
}

static void Main(string[] args)
{
    Action<int> printActionDel = ConsolePrint;
    printActionDel(10);
}

你可以通过直接赋值  或者  new 关键字 来初始化一个 Action代理如下:

Action<int> printActionDel = ConsolePrint;

//Or

Action<int> printActionDel = new Action<int>(ConsolePrint);

一个Action代理可以允许有16个不同类型的输入参数

同样的 匿名函数也可以赋值给Action代理

static void Main(string[] args)
{
    Action<int> printActionDel = delegate(int i)
                                {
                                    Console.WriteLine(i);
                                };

    printActionDel(10);
}

最简单的写法 莫过于用Lambda表达式来赋值

static void Main(string[] args)
{

    Action<int> printActionDel = i => Console.WriteLine(i);
       
    printActionDel(10);
}

所以, 想使用不带返回值的代理时 优先考虑Action

Action 和 Func代理的优势

1、简单快速的定义一个代理

2、代码更简洁

3、兼容性更好

 Points to Remember :
  1. Action delegate is same as func delegate except that it does not return anything. Return type must be void.
  2. Action delegate can have 0 to 16 input parameters.
  3. Action delegate can be used with anonymous methods or lambda expressions.

 

posted @ 2021-03-29 20:21  一个新星的诞生  阅读(12)  评论(0)    收藏  举报