C#高级:巧妙地使用委托改善代码质量

一、如何定义和调用一个委托

说明:

        如以下demo所示,根据入参和出参而定委托的具体类型,调用则使用Invoke方法:

//不入不出
var actions = new Dictionary<string, Action>
{
    { "A", () => Console.WriteLine("Action A") },
    { "B", () => Console.WriteLine("Action B") }
};

string key = "A";
if (actions.ContainsKey(key))
{
    actions[key].Invoke();//调用委托的方法
}


//有入有出
var functions = new Dictionary<string, Func<int, string>>
{
    { "A", x => $"Result of A: {x * 2}" },
    { "B", x => $"Result of B: {x + 10}" }
};

string key = "A";
int parameter = 5;
if (functions.ContainsKey(key))
{
    string result = functions[key].Invoke(parameter);//调用委托的方法
    Console.WriteLine(result);
}

委托的类型总结(按参数区分):

Action  //无入无出
Action<string>  //有入无出
Func<int, string> //有入有出
Func<int>//无入有出

二、使用委托减少if语句 

【需求】

// var datalist = xxx
// 输入1 输出datalist 中width 为10-15的数据
// 输入2 输出datalist 中width 为15-20的数据
// 输入3 输出datalist 中width 为25-35的数据
// 输入4 输出datalist 中width 为35-45的数据
// 输入5 输出datalist 中width 为45-100的数据

using System;
using System.Collections.Generic;
using System.Linq;
// 用委托实现:
// var datalist = xxx
// 输入1 输出datalist 中width 为10-15的数据
// 输入2 输出datalist 中width 为15-20的数据
// 输入3 输出datalist 中width 为25-35的数据
// 输入4 输出datalist 中width 为35-45的数据
// 输入5 输出datalist 中width 为45-100的数据
public class DataType
{
    public int Width { get; set; }
}

public class Program
{
    public static void Main()
    {
        // 示例数据
        var datalist = new List<DataType>
        {
            new DataType { Width = 12 },
            new DataType { Width = 18 },
            new DataType { Width = 28 },
            new DataType { Width = 38 },
            new DataType { Width = 50 }
        };
        
        // 定义过滤器
        var filters = new Dictionary<int, Func<IEnumerable<DataType>, IEnumerable<DataType>>>
        {
            { 1, data => data.Where(d => d.Width >= 10 && d.Width <= 15) },
            { 2, data => data.Where(d => d.Width > 15 && d.Width <= 20) },
            { 3, data => data.Where(d => d.Width > 25 && d.Width <= 35) },
            { 4, data => data.Where(d => d.Width > 35 && d.Width <= 45) },
            { 5, data => data.Where(d => d.Width > 45 && d.Width <= 100) }
        };

        // 输入
        int input = 3;

        // 使用委托进行过滤
        if (filters.TryGetValue(input, out var filter))//输出过滤函数
        {
            var result = filter(datalist);//使用过滤器过滤
            foreach (var item in result)//打印过滤的结果
            {
                Console.WriteLine($"Width: {item.Width}");
            }
        }
    }
}

 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值