c# 三种常见的委托

  参考  《编写高质量代码:改善C#程序的157个建议》 , 尽量使用FCL中的委托声明。

     FCL: FrameWork Class Library

 三种常用:Action、Func、Predicate

小例子:

1.Action :无返回值

复制代码
    private void AddAction(int a, int b)
    {
        Console.WriteLine(a + b);
    }
    static void Main(string[] args)
    {
        TestCSharpClass myTest = new TestCSharpClass();
        Action<int, int> testAction = myTest.AddAction;
        testAction(1, 2);
    }
复制代码

2.Func<T1,T2....,out Tn>:有返回值,

复制代码
    private int AddFuncTest(int a, int b)
    {
        return a + b;
    }
    static void Main(string[] args)
    {
        TestCSharpClass myTest = new TestCSharpClass();
        Func<int, int, int> funcTest = myTest.AddFuncTest;
        Console.WriteLine(funcTest(1,2));
    }
复制代码

3.Predicate<T>  返回bool值。 一个参数。  在查询接口中比较有用

复制代码
    private class PreTestClass
    {
        private int a;
        private int b;
        public PreTestClass(int a0, int b0)
        {
            a = a0;
            b = b0;
        }
        public bool TestBool(int ccc)
        {
            if (a + b >= ccc)
            {
                return true;
            }
            return false;
        }
    }
    static void Main(string[] args)
    {
        PreTestClass testClass = new PreTestClass(1, 2);
        Predicate<int> testPredicate = testClass.TestBool;
        Console.WriteLine(testPredicate(4));
    }
复制代码

 

posted @   sun_dust_shadow  阅读(699)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示