C# - 谓词委托(Predicate Delegate)

本文关键字:Predicate Delegate 谓词 | 更新日期: 2023-09-12 17:40:17

Predicate是委托,如Func 和 Action delegates。它表示包含一组条件的方法,并检查传递的参数是否满足这些条件。谓词委托方法必须采用一个输入参数并返回布尔值 - true 或 false。

Predicate委托在 System 命名空间中定义,如下所示:

谓词签名:public delegate bool Predicate<in T>(T obj);

与其他委托类型相同,Predicate 也可以与任何方法、匿名方法或 lambda 表达式一起使用。

Example: Predicate delegate

static bool IsUpperCase(string str)
{
    return str.Equals(str.ToUpper());
}
static void Main(string[] args)
{
    Predicate<string> isUpper = IsUpperCase;
    bool result = isUpper("hello world!!");
    Console.WriteLine(result);
}

输出:

false

还可以将匿名方法分配给谓词委托类型,如下所示。

Example: Predicate delegate with anonymous method

static void Main(string[] args)
{
    Predicate<string> isUpper = delegate(string s) { return s.Equals(s.ToUpper());};
    bool result = isUpper("hello world!!");
}

还可以将 lambda 表达式分配给谓词委托类型,如下所示。

Example: Predicate delegate with lambda expression

static void Main(string[] args)
{
    Predicate<string> isUpper = s => s.Equals(s.ToUpper());
    bool result = isUpper("hello world!!");
}

注意:

  1. 谓词委托采用一个输入参数和布尔返回类型。
  2. Anonymous method和Lambda表达式可以分配给谓词委托。