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; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具