C# 委托(delegate、Action、Func、predicate)

委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递。事件是一种特殊的委托。

1.委托的特点:

委托类似于 C++ 函数指针,但它们是类型安全的。

委托允许将方法作为参数进行传递。

委托可用于定义回调方法。

委托可以链接在一起;例如,可以对一个事件调用多个方法。

方法不必与委托签名完全匹配。

2.总结:

Delegate至少0个参数,至多32个参数,可以无返回值,也可以指定返回值类型

Func可以接受0个至16个传入参数,必须具有返回值

Action可以接受0个至16个传入参数,无返回值

Predicate只能接受一个传入参数,返回值为bool类型

(1). delegate

delegate我们常用到的一种声明

Delegate至少0个参数,至多32个参数,可以无返回值,也可以指定返回值类型。

例:public delegate int MethodtDelegate(int x, int y);表示有两个参数,并返回int型。

public delegate int MethodDelegate(int x, int y);
private static MethodDelegate method;
static void Main(string[] args)
{
    method = new MethodDelegate(Add);
    Console.WriteLine(method(10,20));
    Console.ReadKey();
}

private static int Add(int x, int y)
{
    return x + y;
}

(2). Action

Action是无返回值的泛型委托。

Action 表示无参,无返回值的委托

Action<int,string> 表示有传入参数int,string无返回值的委托

Action<int,string,bool> 表示有传入参数int,string,bool无返回值的委托

Action<int,int,int,int> 表示有传入4个int型参数,无返回值的委托

Action至少0个参数,至多16个参数,无返回值。

static void Main(string[] args)
{
    Test<string>(Action,"Hello World!");
    Test<int>(Action, 1000);
    Test<string>(p => { Console.WriteLine("{0}", p); }, "Hello World");//使用Lambda表达式定义委托
    Console.ReadKey();
}
public static void Test<T>(Action<T> action, T p)
{
    action(p);
}
private static void Action(string s)
{
    Console.WriteLine(s);
}
private static void Action(int s)
{
    Console.WriteLine(s);
}

  

(3). Func

Func是有返回值的泛型委托

Func<int> 表示无参,返回值为int的委托

Func<object,string,int> 表示传入参数为object, string 返回值为int的委托

Func<object,string,int> 表示传入参数为object, string 返回值为int的委托

Func<T1,T2,,T3,int> 表示传入参数为T1,T2,,T3(泛型)返回值为int的委托

Func至少0个参数,至多16个参数,根据返回值泛型返回。必须有返回值,不可void

static void Main(string[] args)
{
    Console.WriteLine(Test<int,int>(Fun,100,200));
    Console.ReadKey();
}
public static int Test<T1, T2>(Func<T1, T2, int> func, T1 a, T2 b)
{
    return func(a, b);
}
private static int Fun(int a, int b)
{
    return a + b;
}

  

(4) .predicate

predicate 是返回bool型的泛型委托

predicate<int> 表示传入参数为int 返回bool的委托

Predicate有且只有一个参数,返回值固定为bool

例:public delegate bool Predicate<T> (T obj)

static void Main(string[] args)
{
    Point[] points = { new Point(100, 200), 
    new Point(150, 250), new Point(250, 375), 
    new Point(275, 395), new Point(295, 450) };
    Point first = Array.Find(points, ProductGT10);
    Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
    Console.ReadKey();
}
private static bool ProductGT10(Point p)
{
    if (p.X * p.Y > 100000)
    {
        return true;
    }
    else
    {
        return false;
    }
}

  

原文地址:https://www.cnblogs.com/itsone/p/13336325.html