C#委派的學習筆記_Action

 

Action<T> 委託是微軟專門為返回類型為 void 的委託所訂製的
  • 是微軟已經開發好的,放在了 .NET 類別庫中,不再需要我們使用 delegate 關鍵字去定。
  • 用於引用一個 void 返回類型的方法,可以傳遞 16 種不同類型的參數,參數個數最大為 8。
  • Action 的非泛型版本可以呼叫沒有參數的方法。
  • 使用 Action<T> 是一個泛型委託,可以簡化委託的定義,直接使用 Action<T> 就可以呼叫任何返回類型是 void 的方法。







Action委派示範
Student.cs類別

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoCourse
{
    internal class Student
    {
        public static void OutPut1(int num1) => Console.WriteLine(num1);
        public static void OutPut2(int num1, double num2) => Console.WriteLine(num1 * num2);
        public static void OutPut3(int num1, int num2, decimal num3) => Console.WriteLine(num1 * num2 + num3);

    }
}

Program.cs主程式

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoCourse
{
    /// <summary>
    /// 主程式
    /// </summary>
    internal class Program
    {

        static void Main(string[] args)
        {
            Action<int> action1 = new Action<int>(Student.OutPut1);
            action1(200);

            Action<int,double> action2 = new Action<int,double>(Student.OutPut2);
            action2(200, 8.99);

            Action<int,int,decimal> action3 = Student.OutPut3;
            action3(200, 300, 8.99m);
        }
    }
}

注意:在使用 Action<T> 定義類型時,<> 中的資料類型與個數必須與要引用的方法的參數類型和參數個數一致。


非泛型的 Action 委託比較單一,不能帶有任何的參數,並且返回類型也是 void。

Goods.cs類別

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoCourse
{
    internal class Goods
    {
        public static void Show() => Console.WriteLine("你好!");
    }
}

Program.cs主程式

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoCourse
{
    /// <summary>
    /// 主程式
    /// </summary>
    internal class Program
    {

        static void Main(string[] args)
        {
            Action action = Goods.Show;
            action();
        }
    }
}


注意:非泛型委託 Action 與泛型委託 Action<T> 在使用上其實是一樣的,只是泛型委託 Action<T> 可以帶有更多的參數,而非泛型委託 Action 不能帶有參數。

留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題

Architecture(架構) 和 Framework(框架) 有何不同?_軟體設計前的事前規劃的藍圖概念