c# Predicate vs Action vs Func

Predicate

定义

public delegate bool Predicate (P obj);

Example
using System;
  
class GFG {
  
    // Method
    public static bool myfun(string mystring)
    {
        if (mystring.Length < 7)
        {
            return true;
        }
        else 
        {
            return false;
        }
    }
  
    // Main method
    static public void Main()
    {
        Predicate<string> val = myfun;
        Console.WriteLine(val("a code cat"));
    }
}

False

要点
  • 将 Predicate 委托与匿名方法一起使用
Predicate<string> val = delegate(string str)
{
    if (mystring.Length < 7)
    {
        return true;
    }
    else 
    {
        return false;
    };
    val("Geeks");
  • 使用带有 lambda 表达式的 Predicate 委托
Predicate<string> val = str = > str.Equals(str.ToLower());
val("a code cat");

Action

定义

Action delegate is used with those methods whose return type is void。

// One input parameter
public delegate void Action < in P > (P obj);

// Two input parameters
public delegate void Action < in P1, in P2 >(P1 arg1, P2 arg2);

using System;
  
class GFG {
  
    public static void myfun(int p, int q)
    {
        Console.WriteLine(p - q);
    }
  
    static public void Main()
    {
        Action<int, int> val = myfun;
        val(20, 5);
    }
}
重点
  • Action Delegates 和 Function Delegates 之间的唯一区别是 Action Delegates 不返回任何内容

Action val = new Action(myfun);

Action val = myfun;

Action val = delegate(string str)
{
Console.WriteLine(str);
};
val(“a code cat”);

Action val = str = > Console.WriteLine(str);
val(“a code cat”);


Func

语法
public delegate TResult Func<out PResult>();

public delegate TResult Func<in P, out PResult>(P arg);

public delegate TResult Func<in P1, in P2, out PResult>(P1 arg1, P2 arg2);

public delegate TResult Func<in P1, in P2, in P3, in P4, in P05, in P6, in P7, in P8, in P9, in P10, in P11, in P12, in P13, in P14, in P15, in P16, out PResult>(P1 arg1, P2 arg2, P3 arg3, P4 arg4, P5 arg5, P6 arg6, P7 arg7, P8 arg8, P9 arg9, P10 arg10, P11 arg11, P12 arg12, P13 arg13, P14 arg14, P15 arg15, P16 arg16);

Sample
using System;
  
class GFG {
  
    public static int method(int num)
    {
        return num + num;
    }
  
    static public void Main()
    {
        Func<int, int> myfun = method;
        Console.WriteLine(myfun(10));
    }
}
重点
  • Func Delegate 中的最后一个参数始终是一个输出参数,它被视为返回类型。 它通常用于结果

  • 将 Func 委托与匿名方法一起使用

Func<int, int, int> val = delegate(int x, int y, int z)
{
return x + y + z;
};

  • 将 Func 委托与 lambda 表达式一起使用

Func<int, int, int, int> val = (int x, int y, int z) = > x + y + z;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值