常见泛型委托

1.Action

Action<>委托可以拥有n个参数(0-16),无返回值。

class Program
{
    static void Method1()
    {
        Console.WriteLine("without any parameter");
    }
    static void Method2(int i)
    {
        Console.WriteLine($"the int is {i}");
    }
    static void Method3(string s, double d)
    {
        Console.WriteLine($"the string is {s}, the double is {d}");
    }
    static void Main()
    {
        Action A1 = Method1;
        Action<int> A2 = Method2;
        Action<string, double> A3 = Method3;
        A1();
        A2(1);
        A3("hello", 3.14);
        Console.ReadKey();
    }
}
View Code

输出结果如下:

without any parameter
the int is 1
the string is hello, the double is 3.14

2.Func

Func<>委托可以拥有n个参数(1-16),类型参数中的最后一个作为返回值类型。因此类型参数不能为空,至少有一个返回类型。

class Program
{
    static int Method1(int i)
    {
        return i * 10;
    }
    static string Method2(int a, double d)
    {
        return (a + d).ToString();
    }
    static void Main()
    {
        Func<int, int> F1 = Method1;
        Func<int, double, string> F2 = Method2;
        Console.WriteLine($"{F1(10)}");
        Console.WriteLine($"{F2(1, 3.14)}");
        Console.ReadKey();
    }
}
View Code

输出结果如下:

100
4.14

3.Predicate

Predicate<>委托拥有一个参数,其返回值为bool型。

class Program
{
    static bool Method(int i)
    {
        return i > 0 ? true : false;
    }
    static void Main()
    {
        Predicate<int> P = Method;
        Console.WriteLine(P(10));
        Console.ReadKey();
    }
}
View Code

输出结果如下:

True

通过匿名方法使用Predicate<>,

class Program
{
    static void Main()
    {
        var anomynous = new Predicate<int>(delegate (int i) { return i > 0 ? true : false; });
        Console.WriteLine(anomynous(1));
        Console.ReadKey();
    }
}
View Code

输出结果如下:

True

转载于:https://www.cnblogs.com/jizhiqiliao/p/9849753.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值