Action是無返回值的泛型委托
可以使用 Action<T1, T2, T3, T4> 委托以參數形式傳遞方法,而不用顯式聲明自定義的委托。封裝的方法必須與此委托定義的方法簽名相對應。也就是說,封裝的方法必須具有四個均通過值傳遞給它的參數,并且不能返回值。(在 C# 中,該方法必須返回 void)通常,這種方法用于執行某個操作。
1、Action 表示無參,無返回值的委托
2、 Action<int,string> 表示有傳入參數int,string無返回值的委托
3、Action<int,string,bool> 表示有傳入參數int,string,bool無返回值的委托
4、 Action<int,int,int,int>
表示有傳入4個int型參數,無返回值的委托
5、 Action至少0個參數,至多16個參數,無返回值。
class Program
{
static void Main(string[] args)
{
//循環調用,action不傳參
List<Action> actions = new List<Action>();
for (int i = 0; i < 10; i++)
{
//因為是按地址傳遞參數,所以要聲明變量,不如結果都是10
int k = i;
actions.Add(() => Console.WriteLine(k));
}
foreach (Action a in actions)
{
a();
}
//傳遞兩個參數
Action<string, int> action = new Action<string, int>(ShowAction);
Show("張三",29,action);
//傳遞一個參數
Show("張三",o=>Console.WriteLine(o));
//不傳遞參數調用
Show(()=>Console.WriteLine("張三"));
}
public static void ShowAction(string name, int age)
{
Console.WriteLine(name + "的年齡:" + age);
}
public static void Show(string name, int age, Action<string, int> action)
{
action(name, age);
}
public static void Show(string name, Action<string> action)
{
action(name);
}
public static void Show(Action action)
{
action();
}
}
輸出結果:
0
1
2
3
4
5
6
7
8
9
張三的年齡:29
張三
張三
該文章在 2024/1/24 23:35:19 編輯過