Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Func Delegate generic trong C#

Func<T1, T2, ..., TResult> là delegate generic đại diện cho phương thức có trả về giá trị (khác với Action trả về void). Có từ 0 đến 16 tham số đầu vào, tham số cuối cùng là kiểu trả về.

Các ví dụ Func với số tham số khác nhau

// 1 tham số int → string
Func one = p => string.Format("{0}", p);

// 2 tham số (bool, long) → string
Func two = (q, p) => string.Format("{0} and {1}", q, p);

// 2 tham số (bool, int) → string
Func three = (q, p) => string.Format("{0} and {1}", q, p);

// 1 tham số decimal → string
Func four = p => string.Format("{0}", p);

Mã nguồn hoàn chỉnh

using System;
using System.IO;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 1 tham số int → string
            Func one = p => string.Format("{0}", p);
            
            // 2 tham số bool, long → string
            Func two = (q, p) => string.Format("{0} and {1}", q, p);
            
            // 2 tham số bool, int → string
            Func three = (q, p) => string.Format("{0} and {1}", q, p);
            
            // 1 tham số decimal → string
            Func four = p => string.Format("{0}", p);
            
            Console.WriteLine(one.Invoke(25));              // 25
            Console.WriteLine(two.Invoke(false, 76756566)); // False and 76756566
            Console.WriteLine(three.Invoke(true, 50));      // True and 50
            Console.WriteLine(four.Invoke(1.2m));           // 1.2
        }
    }
}

Kết quả

25
False and 76756566
True and 50
1.2

Các biến thể Func

DelegateTham số nhậpTrả về
Func0TResult
Func1TResult
Func2TResult
.........
Func16TResult

Func vs Action vs Predicate

DelegateTrả vềDùng cho
Func<..., TResult>TResultTính toán, mapping, transformation
Action<...>voidSide effect (log, write, modify)
Predicate<T>boolFilter, condition check

Ứng dụng thực tế

  • Strategy pattern: Func processor
  • Factory: Func creator
  • LINQ selectors: Select(Func), Where(Func) (Predicate)
  • Callback với kết quả trả về
  • Memoization, caching