Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ประเภท Func แบบ Generic ใน C#

Func<T1, T2, ..., TResult> เป็น Delegate แบบ Generic ที่อ้างอิงเมธอดที่มี ค่าคืน (Return Value) รองรับพารามิเตอร์ 0-16 ตัว ตัวสุดท้ายคือ Return Type

ตัวอย่าง 4 รูปแบบ Func

using System;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 1. รับ int คืน string
            Func one = p => string.Format("{0}", p);
            
            // 2. รับ bool, long คืน string
            Func two = (q, p) => string.Format("{0} and {1}", q, p);
            
            // 3. รับ bool, int คืน string
            Func three = (q, p) => string.Format("{0} and {1}", q, p);
            
            // 4. รับ decimal คืน string
            Func four = p => string.Format("{0}", p);
            
            Console.WriteLine(one.Invoke(25));
            Console.WriteLine(two.Invoke(false, 76756566));
            Console.WriteLine(three.Invoke(true, 50));
            Console.WriteLine(four.Invoke(1.2m));
        }
    }
}

ผลลัพธ์

25
False and 76756566
True and 50
1.2

ต่างจาก Action: Action ไม่มีค่าคืน (void), Func ต้องมีค่าคืนเสมอ