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;