标签:
///我们经常使用一些匿名委托来处理一些逻辑
///但是在某些情况下,有可能委托是null,要是直接执行可能会抛异常
///所以提供此扩展方法,直接可以使用例如 action.Execute() 来执行
namespace System { public static class ActionExtension { public static void Execute(this Action action) { if (action != null) { action(); } } public static void Execute<T>(this Action<T> action, T obj) { if (action != null) { action(obj); } } } }
///此段一目明了,模仿 string.IsNullOrEmpty 来判断集合是否为null还是空
namespace System.Linq { using System.Collections.Generic; public static class LinqExtension { /// <summary> /// 判定一个IEnumerable集合是否为Null或者是空集合 /// </summary> /// <typeparam name="TSource"></typeparam> /// <param name="collection"></param> /// <returns></returns> public static bool IsNullOrEmpty<TSource>(this IEnumerable<TSource> collection) { return collection == null || !collection.Any(); } } }
///利用序列化和流执行对象深拷贝
namespace System { using System; using System.IO; using System.Runtime.Serialization; public static class ExtensionMethods { public static T DeepClone<T>(this object source) where T : class { if (source == null) { return default(T); } using (MemoryStream stream = new MemoryStream()) { var dataContractSerializer = new DataContractSerializer(source.GetType()); dataContractSerializer.WriteObject(stream, source); stream.Position = 0; return (T)dataContractSerializer.ReadObject(stream); } } } }
标签:
原文地址:http://www.cnblogs.com/seraphim/p/4208825.html