(C#) 内置 委托(1)

来源:互联网 发布:金融证券软件 编辑:程序博客网 时间:2024/05/21 11:05

    上篇文章简单介绍了一下什么是委托?但是每次都内定义一个委托,感觉有些麻烦,所以微软为了为人民服务,提出了内置委托,让你直接使用就好。

    对于内置委托,最常用的主要有三个,Action<>,Func<>,Predicate<>

    对于内置,怎么理解?其实就是少去了定义的过程。

    对于Action<>的出现是在.NetFramework2.0的时候出现的,当时还只能够传入4个值,渐渐的在.NetFramework3.0的支持下,出现了Func<>,满足了对于返回值的要求。现在不管是Action<>还是Func<>最多可以封装16个参数


举例说明:

ACTION<T>demo:

    利用三个参数,来对一句话进行设置:

 //Action<>委托的一个目标        static void DisplayMessage(string msg, ConsoleColor txtColor, int printCount)        {            //设置命令行文本的颜色(获取前景色)            ConsoleColor previous = Console.ForegroundColor;            Console.ForegroundColor = txtColor;            //循环的次数            for (int i = 0; i < printCount; i++)            {                Console.WriteLine(msg);            }            //重置颜色            Console.ForegroundColor = previous;        }
看控制台的调用:

 static void Main(string[] args)        {            //使用Action<>委托来指向DisplayMessage            Action<string, ConsoleColor, int> actionTarget = DisplayMessage;            actionTarget("Action Message!", ConsoleColor.Red, 5);            console.readline();
Action<>是没有返回值的,看显示结果:


而对于Func<>来说,最后一个委托则封装的返回值的类型:

 //简单的Add方法        static int Add(int x, int y)        {            return x + y;        }
看控制台调用:

//使用Func<>委托来指向Add            Func<int, int, int> funcTarget = new Func<int, int, int>(Add);            int result = funcTarget.Invoke(40, 40);            Console.WriteLine("40+40={0}", result);
    定义两个参数int类型,返回一个int类型的返回值。

对于内置委托的使用,简化了自定义委托带给我们的繁琐,不过只是讲述了一下Action<>和Func<>的使用,未完待续……

2 0
原创粉丝点击