欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > 基于扩展方法实现C#安全集合操作工具包(含完整源码)

基于扩展方法实现C#安全集合操作工具包(含完整源码)

2025/3/13 15:49:24 来源:https://blog.csdn.net/WangMing_X/article/details/146195986  浏览:    关键词:基于扩展方法实现C#安全集合操作工具包(含完整源码)

一、安全集合操作的价值

在日常开发中,集合操作引发的NullReferenceExceptionIndexOutOfRangeException等异常占比高达35%。本工具包通过扩展方法实现以下核心场景的安全防护:

  1. 安全索引访问 防止数据绑定、列表遍历时的越界崩溃
  2. 空集合防御处理 避免foreach空集合导致的逻辑异常
  3. 批量操作增强 简化集合合并、筛选等批量操作
  4. 深拷贝支持 解决引用类型集合修改时的副作用问题

二、完整实现代码

using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;/// <summary>
/// 集合安全操作扩展工具包
/// </summary>
public static class SafeCollectionExtensions
{/// <summary>/// 安全获取集合元素[6](@ref)/// </summary>/// <param name="index">元素索引</param>/// <param name="defaultValue">默认返回值</param>/// <returns>存在返回元素,否则返回默认值</returns>public static T SafeGet<T>(this IList<T> source, int index, T defaultValue = default){if (source == null) return defaultValue;return (index >= 0 && index < source.Count) ? source[index] : defaultValue;}/// <summary>/// 判断集合是否为空(支持null检测)/// </summary>public static bool IsNullOrEmpty<T>(this IEnumerable<T> source){return source == null || !source.Any();}/// <summary>/// 安全批量添加元素[3](@ref)/// </summary>/// <param name="items">待添加元素集合</param>public static void AddRangeSafe<T>(this IList<T> target, IEnumerable<T> items){if (target == null || items.IsNullOrEmpty()) return;foreach (var item in items.Where(item => item != null)){target.Add(item);}}/// <summary>/// 深度克隆集合[5](@ref)/// </summary>/// <typeparam name="T">可序列化类型</typeparam>public static List<T> DeepClone<T>(this IEnumerable<T> source){if (source.IsNullOrEmpty()) return new List<T>();var serializer = new DataContractJsonSerializer(typeof(List<T>));using (var ms = new MemoryStream()){serializer.WriteObject(ms, source.ToList());ms.Position = 0;return (List<T>)serializer.ReadObject(ms);}}
}

三、实战应用教程

场景1:安全读取配置数据

var configList = GetConfigFromAPI(); // 可能返回null// 传统方式
if (configList != null && configList.Count > 5) 
{var value = configList[5];
}// 扩展方法方式
var safeValue = configList.SafeGet(5, "default");

场景2:批量导入数据校验

// 原始集合
List<Product> products = new List<Product>();// 待导入数据(可能包含null)
var importedData = GetExternalData();// 安全批量添加
products.AddRangeSafe(importedData?.Where(p => p.IsValid));

场景3:集合状态检测

void ProcessOrders(IEnumerable<Order> orders)
{if (orders.IsNullOrEmpty()) {ShowAlert("无待处理订单");return;}// 处理逻辑...
}

四、技术特性解析

方法名称

安全机制

性能优化点

SafeGet

空引用检查 + 索引范围验证

避免多次null判断

AddRangeSafe

空集合过滤 + 元素有效性检查

使用Where过滤减少循环次数

DeepClone

JSON序列化实现深度复制

MemoryStream减少内存分配

IsNullOrEmpty

组合null判断与Any()延迟执行

优于Count属性的O(1)时间复杂度


五、本工具包的优势

通过扩展方法实现的集合安全操作包具有以下优势:

零入侵:不修改原始集合类型代码

高复用:通过using指令全局生效

强兼容:支持List<T>Array等所有IEnumerable实现

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词