c# 三種泛型委託Func、Action、Predicate

Func<T>委託有返回值的泛型委託,封裝了最多可以傳入16個參數,方法返回void的不能使用Func<T>委託。
Action<T>委託返回值爲void,封裝了最多可以傳入16個參數,用法與Func<T>相同。
Predicate<T>委託返回值爲bool類型的委託,可以被Func<T>代替。

使用示例:

public string Show1(Func<string, string> func)
        {
            return func("0");
        }

        public void Show()
        {
            //public delegate int WithReturn(int a, int b);
            //WithReturn withReturn = (a, b) => { return a + b; };

            //多行代碼
            Func<string, string> func = param =>
            {
                param += "1";
                param += "2";
                return param;
            };
            Console.WriteLine(Show1(func));//輸出:012

            //一個參數
            Func<string, string> func2 = s => $"test{s.ToUpper()}";
            Console.WriteLine(func2("sss"));//輸出:testSSS

            //多個參數
            Func<int, int, int> func1 = (x, y) => x + y;
            Console.WriteLine(func1(1, 2));//輸出:3

            //閉包
            int someVal = 5;
            Func<int, int> f = x => x + someVal;
            Console.WriteLine(f(2));//輸出7

            //Action使用
            Action<int> action = (x) => Sub(x);
            action(11);

            //Predicate使用
            Predicate<int> predicate = (x) => { return x > 0; };
            Console.WriteLine(predicate(1));
        }

        public void Sub(int x)
        {
            Console.WriteLine(x);
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章