C#委托之Action、Func与Predicate用法

C#委托之Action与Func用法
一、Action,可以传入参数,没有返回值的委托
  1、调用方法

static void Main(string[] args)
 {
      Action<int, int> addcalc = new Action<int, int>(AddCalc);
      addcalc(2, 3);
      Console.ReadKey();
 }
 static void AddCalc(int x, int y)
 {
     Console.WriteLine(x + y);
 }

  2、使用lambda表示式

static void Main(string[] args)
 {
      Action<int, int> addcalc = ((x, y) => Console.WriteLine(x+y));
      addcalc(2, 3);
      Console.ReadKey();
 }

  3、作为参数传

static void Main(string[] args)
{
  Action<string> a1 = (p => Console.WriteLine("方法一,参数值:" + p));
  Action<string> a2 = (p => Console.WriteLine("方法二,参数值:" + p));
     AddCalc(a1, "输入参数1");//调用AddCalc方法,传入委托作为参数
     AddCalc(a2, "输入参数2");
     Console.ReadKey();
}
static void AddCalc<T>(Action<T> action,T inputParam)
{
    action(inputParam);
}

二、Func,可以传入参数,必须有返回值的委托
 1、调用方法

static void Main(string[] args)
 {
       Func<string> f = new Func<string>(ShowMessage);
       string result = f();//调用委托。
       Console.ReadKey();
 }
 static string ShowMessage()
 {
     return "welcome to zhengzhou";
 }

 2、使用lambda表达式

static void Main(string[] args)
{
       ////实例化一个委托,注意不加大括号,写的值就是返回值,不能带return
       Func<string> f1 = () => "welcome to delegate world";
       //实例化另一个委托,注意加大括号后可以写多行代码,但是必须带return
       Func<string> f2 = () =>
       {
            return "Welcome to delegate world";
       };
       Func<string, string> f3 = x => x.ToUpper();

       string result1 = f1();//调用委托
       string result2 = f2();
       string result3 = f3("abc");
       Console.ReadKey();
 }

 3、作为参数传递

static void Main(string[] args)
{
     //实例化一个委托,注意不加大括号,写的值就是返回值,不能带return
     Func<int, string> fc1 = (p) => string.Format("传入了参数{0}", p);
     //实例化另一个委托,注意加大括号后可以写多行代码,但是必须带return
     Func<string, string> fc2 = (p) =>
       {
            return string.Format("传入了参数{0}", p);
       };
       string result = Transfer<int>(fc1, 1);//调用委托
       string result2 = Transfer<string>(fc2,"hello");
       Console.ReadKey();
  }
  static string Transfer<T>(Func<T, string> func, T inputParam)
   {
      return func(inputParam);
   }

三、Predicate一个传入参数,返回一个bool类型的值

class Program
    {
        static Predicate<int> myPredicate;
        static int[] myNum = new int[8] { 12, 33, 89, 21, 15, 29, 40, 52 };
        public static int[] myResult;
        static void Main(string[] args)
        {
            myPredicate = delegate(int curNum)
            {
                if (curNum % 2 == 0) return true;
                else return false;
            };
            myResult = Array.FindAll(myNum, myPredicate);
            for (int i = 0; i < myResult.Length; i++)
            {
                Console.WriteLine(myResult[i]);
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值