天天看點

C# 中的 Action, Func, EventHandler 和 EventHandler<TEventArgs>

C# 中常用内置委托

Action

,

Func

,

EventHandler

EventHandler<TEventArgs>

介紹

Action Delegate

封裝一個沒有傳回值的方法

樣例

public static void Main()
    {
        Action showMethod = DisplayToConsole;
        showMethod();
        Console.ReadKey();
    }


    static void DisplayToConsole()
    {
        Console.WriteLine("hello");
    }

           

Action <T > Delegate

封裝一個沒有傳回值有一個參數的方法

樣例

public static void Main()
    {
        Action<string> messageTarget = ShowMessage;
        messageTarget("Hello, World!");
        Console.ReadKey();
    }

    static void ShowMessage(string message)
    {
        Console.WriteLine(message);
    }

           

其它

Action

委托

C# 中的 Action, Func, EventHandler 和 EventHandler&lt;TEventArgs&gt;

Action 最多可以支援16個參數,但所有方法均無傳回值。

Func <TResult > Delegate

代表有一個

TResult

類型的傳回值沒有參數的方法

樣例

static void Main(string[] args)
        {
            Func<string> func = GetValue;
            string value = func();
            Console.WriteLine(value);
            Console.ReadKey();
        }

        static string GetValue()
        {
            return "hello";
        }

           

Func <T,TResult > Delegate

代表有一個

TResult

類型的傳回值,有一個

T

類型參數的方法

樣例

static void Main(string[] args)
        {
            Func<int,string> func = GetValue;
            string value = func(10);
            Console.WriteLine(value);
            Console.ReadKey();
        }

        static string GetValue(int num)
        {
            int count=0;
            for (int i = 0; i < num; i++)
            {
                count += i;
            }
            return count.ToString();
        }
           

其它

Func

委托

C# 中的 Action, Func, EventHandler 和 EventHandler&lt;TEventArgs&gt;

Func 最多可以支援16個參數,但所有方法均有一個類型為

TResult

的傳回值。

EventHandler Delegate

表示将處理沒有事件資料的事件方法。

[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public delegate void EventHandler(object sender, EventArgs e);
           

參數

sender

:事件來源

e

:不包含事件資料的對象

樣例

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Counter c = new Counter(new Random().Next(10));
            c.ThresholdReached += c_ThresholdReached;

            Console.WriteLine("press 'a' key to increase total");
            while (Console.ReadKey(true).KeyChar == 'a')
            {
                Console.WriteLine("adding one");
                c.Add(1);
            }
        }

        static void c_ThresholdReached(object sender, EventArgs e)
        {
            Console.WriteLine("事件被觸發");
            Console.ReadKey();
        }
    }

    class Counter
    {
        private int threshold;
        private int total;

        public Counter(int passedThreshold)
        {
            threshold = passedThreshold;
        }

        public void Add(int x)
        {
            total += x;
            if (total >= threshold)
            {
                if (ThresholdReached != null)
                {
                    ThresholdReached(this, null);
                }
            }
        }


        public event EventHandler ThresholdReached;
    }

}
           

EventHandler <TEventArgs > Delegate

表示将處理包含事件資料的事件方法。

[System.Serializable]
public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);
           

參數

TEventArgs

:事件資料類型

sender

:事件來源

e

:包含事件資料的對象

樣例

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Counter c = new Counter(new Random().Next(10));
            c.ThresholdReached += c_ThresholdReached;

            Console.WriteLine("press 'a' key to increase total");
            while (Console.ReadKey(true).KeyChar == 'a')
            {
                Console.WriteLine("adding one");
                c.Add(1);
            }
        }

        static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e)
        {
            Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold,  e.TimeReached);
            Environment.Exit(0);
        }
    }

    class Counter
    {
        private int threshold;
        private int total;

        public Counter(int passedThreshold)
        {
            threshold = passedThreshold;
        }

        public void Add(int x)
        {
            total += x;
            if (total >= threshold)
            {
                ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
                args.Threshold = threshold;
                args.TimeReached = DateTime.Now;
                OnThresholdReached(args);
            }
        }

        protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
        {
            EventHandler<ThresholdReachedEventArgs> handler = ThresholdReached;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        public event EventHandler<ThresholdReachedEventArgs> ThresholdReached;
    }

    public class ThresholdReachedEventArgs : EventArgs
    {
        public int Threshold { get; set; }
        public DateTime TimeReached { get; set; }
    }
}
           

繼續閱讀