C#的Action和Func委托
Action委托:
1.声明和使用不带参数的 Action
委托:
Action myAction = () => Console.WriteLine("Hello World!"); myAction();
2.声明和使用带有一个参数的 Action
委托:
Action<string> myAction = (message) => Console.WriteLine(message); myAction("Hello World!");
3.声明和使用带有两个参数的 Action
委托:
Action<string, int> myAction = (message, number) => Console.WriteLine($"{message} {number}"); myAction("Hello", 123);
4.使用匿名方法创建 Action
委托:
Action myAction = delegate() { Console.WriteLine("Hello World!"); }; myAction();
5.使用 lambda 表达式创建 Action
委托:
Action myAction = () => Console.WriteLine("Hello World!"); myAction();
6.将方法作为 Action
委托的参数:
public void DisplayMessage(string message) { Console.WriteLine(message); } Action myAction = DisplayMessage; myAction("Hello World!");
7.将实例方法作为 Action
委托的参数:
public class MyClass { public void DisplayMessage(string message) { Console.WriteLine(message); } } MyClass myClass = new MyClass(); Action myAction = myClass.DisplayMessage; myAction("Hello World!");
Func委托:
1.使用Func<T, TResult>
委托调用一个方法:
public class Program { public static void Main(string[] args) { Func<int, string> func = IntToString; string result = func(123); Console.WriteLine(result); // 输出: 123 } public static string IntToString(int number) { return number.ToString(); } }
2.使用Func<T, TResult>
委托在LINQ查询中:
public class Program { public static void Main(string[] args) { string[] names = { "Tom", "Dick", "Harry" }; Func<string, bool> nameFilter = name => name.Length > 4; var longNames = names.Where(nameFilter).ToList(); longNames.ForEach(name => Console.WriteLine(name)); // 输出: Harry } }
3.使用Func<T, TResult>
委托在Array.Sort
中指定排序方法:
public class Program { public static void Main(string[] args) { Person[] people = { new Person { Name = "Tom", Age = 30 }, new Person { Name = "Dick", Age = 25 }, new Person { Name = "Harry", Age = 35 } }; Array.Sort(people, (p1, p2) => p1.Name.CompareTo(p2.Name)); foreach (var person in people) { Console.WriteLine($"{person.Name} - {person.Age}"); } } } public class Person { public string Name { get; set; } public int Age { get; set; } }