第十一篇 .NET高级技术之内置泛型委托

Func、Action

一.如果不是声明为泛型委托 委托的类型名称不能重载,也就是不能名字相同类型参数不同

二..Net中内置两个泛型委托Func、Action(在“对象浏览器”的mscorlib的System下),日常开发中基本不用自定义委托类型了。

三.Func是有返回值的委托;Action是没有返回值的委托

 四。.Action<T>是.NET Framework内置的泛型委托,可以使用Action<T>委托以参数形式传递方法,而不用显示声明自定义的委托。封装的方法必须与此委托定义的方法签名相对应。也就是说,封装的方法必须具有一个通过值传递给它的参数,并且不能有返回值。

五.实例

using System;

using System.Collections.Generic;

扫描二维码关注公众号,回复: 6266375 查看本文章

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace mydelSour

{

   public class Class4

    {

       

        

         //声明一个无参数的方法

        public  static void f1()

        {

            Console.Write("abc");

        }

        //声明一个带参数有返回类型的方法

        public static string f2(string a, int b)

        {

            return a;

        }

      

    }

}

   Action ac = new Action(Class4.f1);//action 是没有返回值的委托是内置的委托

            ac();//指向没有参数的实现方法

            /*func是一个有参数有返回类型的内置委托,前面的参数都是实现方法的参数

             最后一个是实现方法的返回类型

            Func<string, int, string> fc = new Func<string, int, string>(Class4.f2);

            <>括号里面 第一个string 对应  public static string f2(string a, int b)

             

              第一个string 对应 f2中 string a

              第二个 int   对应 f2中 int b

             */

            Func<string, int, string> fc = new Func<string, int, string>(Class4.f2);

            string acc = fc("aaaa", 1);

            Console.Write(acc);

            Console.ReadKey();

更多技术请关注

猜你喜欢

转载自www.cnblogs.com/dullbaby/p/10910769.html