C# 委托类型 Action、Func与Predicate

一.前言

   在C#中,Action、Func与Predicate都是.Net类库的内置委托类型,可以让我们更加简洁便利地使用委托。

二.使用

  在使用委托时,都需要定义一个委托类型,然后定义一个符合委托类型签名的方法。创建委托,并将方法与委托关联,最后调用委托。例子如下。

//定义委托类型
public delegate string Attack(int point);
public class Demo
{
    public string Fire(int point)
    {
        return "火属性伤害:" + point + "点\n";
    }
    public string Ice(int point)
    {
        return "冰属性伤害:" + point + "点\n";
    }
}

public class Program
{
    //调用
    public static void Main(string[] args)
    {
        //声明委托变量
        Attack attack;

        Demo demo = new Demo();

        //初始化委托变量,将方法和委托关联
        attack = new Attack(demo.Fire);
        //向委托添加方法
        attack += demo.Ice;
        //向委托减方法
        //attack -= demo.Ice;
        //调用委托
        string result = attack(100);
        Console.WriteLine(result);
    }

}

  委托的使用,可以参考:https://www.cnblogs.com/shadoll/p/14507166.html

  这里定义的委托类型是只有一个参数,如果有两个或更多参数的委托类型,则需要重新定义。Action、Func、Precidate这几个内置的委托类型,可以简化需要定义各种参数类型或数量的委托类型的操作。

  Action委托具有Action<T>、Action<T1,T2>......Action<T1,T2,...T16>多达16个的重载,其中参数为泛型中的类型参数T,几乎包含所有可能存在的无返回值的委托类型。

  Func委托具有Func<TResult>、Func<T1,TResult>、Func<T1,T2...T16,TResult>多达17个的重载,T1...T16为参数,TResult为返回值类型。

  Precidate委托为Precidate<T>,只有一种,T为参数,返回值为布尔类型true或false。

Action<string> action = delegate (string a) { Console.WriteLine(a); };
action("233");

Func<string, string> func = delegate (string a) { return a; };
func("233");

Predicate<int> predicate = delegate (int a) { return a > 0; };
predicate(233);

三.总结

  1.Action、Func、Predicate都是结合委托来使用,为.Net类库自带的委托类型。

  2.底层通过泛型实现,多种重载,能满足大多数使用委托类型多个参数、各种类型参数或各种类型返回值的场景。

posted @ 2021-04-03 17:37  shine声  阅读(407)  评论(0编辑  收藏  举报