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; }
}
复制代码

 

posted @   Cmale  阅读(1290)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示