.NET 实用扩展方法(持续更新...)

1. 字符串转换为可空数值类型(int, long, float...类似)

    /// <summary>
/// 将字符串转换成32位整数,转换失败返回null
/// </summary>
/// <param name="str">转换的字符串</param>
/// <returns>转换之后的整数,或null</returns>
public static int? TryParseToInt32(this string str)
{
if (string.IsNullOrWhiteSpace(str))
return null;
var result = 0;
if (int.TryParse(str, out result))
return result;
else
return null;
}

2. 去除子字符串

    /// <summary>
/// 去除子字符串
/// </summary>
/// <param name="str">原字符串</param>
/// <param name="substring">要去除的字符串</param>
/// <returns>去除子字符串之后的结果</returns>
public static string DeSubstring(this string str, string substring)
{
if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(substring) || !str.Contains(substring))
{
return str;
} return Regex.Replace(str, Regex.Escape(substring), string.Empty);
} /// <summary>
/// 去除子字符串
/// </summary>
/// <param name="str">原字符串</param>
/// <param name="substrings">要去除的子字符串</param>
/// <returns>去除子字符串之后的结果</returns>
public static string DeSubstring(this string str, params string[] substrings)
{
if (string.IsNullOrEmpty(str))
return str;
if (substrings == null)
return str;
var newStr = str;
foreach (var item in substrings)
{
newStr = newStr.DeSubstring(item);
}
return newStr;
}

3. 获取子序列

    /// <summary>
/// 获取子序列
/// </summary>
/// <typeparam name="T">序列中元素类型</typeparam>
/// <param name="source">源数据</param>
/// <param name="startIndex">开始索引(返回时包括)</param>
/// <param name="endIndex">结束索引(返回时包括)</param>
/// <returns>子序列</returns>
public static IEnumerable<T> SubEnumerable<T>(this IEnumerable<T> source, int startIndex, int endIndex)
{
if (source == null)
yield return default(T);
var length = source.Count();
if (startIndex < 0 || endIndex < startIndex || startIndex >= length || endIndex >= length)
throw new ArgumentOutOfRangeException(); var index = -1;
foreach (var item in source)
{
index++;
if (index < startIndex)
continue;
if (index > endIndex)
yield break;
yield return item;
}
}

4. 通过指定键对序列去重, 不必实现IEqualityComparer接口

    /// <summary>
/// 通过对指定的值进行比较返回序列中的非重复元素。
/// </summary>
/// <typeparam name="T">序列中元素类型</typeparam>
/// <typeparam name="TResult">指定的比较属性类型</typeparam>
/// <param name="source">源数据</param>
/// <param name="selector">应用于每个元素的转换函数</param>
/// <returns>一个包含源序列中的按指定属性非重复元素</returns>
public static IEnumerable<T> Distinct<T, TResult>(this IEnumerable<T> source, Func<T, TResult> selector)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (selector == null)
throw new ArgumentNullException(nameof(selector));
var set = new HashSet<TResult>();
foreach (var item in source)
{
var result = selector(item);
if (set.Add(result))
{
yield return item;
}
}
}

5. 获取序列中重复的元素序列, 原理和去重类似

    /// <summary>
/// 通过对指定的值进行比较返回序列中重复的元素
/// </summary>
/// <typeparam name="T">序列中的数据类型</typeparam>
/// <typeparam name="TResult">指定的比较属性类型</typeparam>
/// <param name="source">源数据</param>
/// <param name="selector">应用于每个元素的转换函数</param>
/// <returns>一个包含源序列中的按指定元素的重复元素</returns>
public static IEnumerable<T> Identical<T>(this IEnumerable<T> source)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
var setT = new HashSet<T>();
foreach (var item in source)
{
if (!setT.Add(item))
{
yield return item;
}
}
} /// <summary>
/// 通过对指定的值进行比较返回序列中重复的元素
/// </summary>
/// <typeparam name="T">序列中的数据类型</typeparam>
/// <typeparam name="TResult">指定的比较属性类型</typeparam>
/// <param name="source">源数据</param>
/// <param name="selector">应用于每个元素的转换函数</param>
/// <returns>一个包含源序列中的按指定元素的重复元素</returns>
public static IEnumerable<T> Identical<T, TResult>(this IEnumerable<T> source, Func<T, TResult> selector)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (selector == null)
throw new ArgumentNullException(nameof(selector));
var setTResult = new HashSet<TResult>();
foreach (var item in source)
{
var result = selector(item);
if (!setTResult.Add(result))
{
yield return item;
}
}
}

6. 使用注解对实体进行验证, 可用在除ASP.NET MVC之外的任一框架中(MVC已内置), 需引用System.ComponentModel.DataAnnotations类库及命名空间

    /// <summary>
/// 通过使用验证上下文和验证结果结合, 确定指定的对象是否有效
/// </summary>
/// <param name="instance">要验证的对象</param>
/// <param name="validationResults">用于包含每个失败的验证的集合</param>
/// <returns>如果对象有效,为 true, 否则为 false</returns>
public static bool TryValidate(this object instance, ICollection<ValidationResult> validationResults = null)
{
var context = new ValidationContext(instance);
return Validator.TryValidateObject(instance, context, validationResults, true);
} /// <summary>
/// 通过使用验证上下文和验证结果结合, 确定指定的方法参数是否有效
/// </summary>
/// <param name="instance">要验证的方法所属对象</param>
/// <param name="methodName">类中要验证的方法名称</param>
/// <param name="values">方法参数的值</param>
/// <param name="validationResults">用于包含每个失败的验证的集合</param>
/// <returns>如果参数有效,为 true, 否则为 false</returns>
public static bool TryValidate(this object instance, string methodName, object[] values, ICollection<ValidationResult> validationResults = null)
{
var typeOfInstance = instance.GetType();
var methodInfo = typeOfInstance.GetMethod(methodName, values.Select(p => p?.GetType() ?? typeof(object)).ToArray());
if (methodInfo == null)
{
//查找可能存在的泛型方法
methodInfo = typeOfInstance
.GetMethods()
.FirstOrDefault(p => p.Name == methodName
&& p.IsGenericMethod
&& p.GetParameters().Length == values.Length);
}
if (methodInfo == null)
throw new ArgumentException("找不到指定的方法,请检查方法名或者参数数组是否存在匹配");
var paramInfos = methodInfo.GetParameters();
bool isValid = true;
for (var i = 0; i < values.Length; i++)
{
var value = values[i];
var paramInfo = paramInfos.ElementAt(i);
var context = new ValidationContext(paramInfo);
context.DisplayName = paramInfo.Name;
var attrs = paramInfo.GetCustomAttributes<ValidationAttribute>();
isValid = isValid & Validator.TryValidateValue(value, context, validationResults, attrs);
}
return isValid;
} /// <summary>
/// 通过使用验证上下文和验证结果结合, 确定指定的方法参数是否有效
/// </summary>
/// <param name="instance">要验证的方法所属对象</param>
/// <param name="methodName">类中要验证的方法名称</param>
/// <param name="values">方法参数值</param>
public static void Validate(this object instance, string methodName, object[] values)
{
var typeOfInstance = instance.GetType();
var methodInfo = typeOfInstance.GetMethod(methodName, values.Select(p => p?.GetType() ?? typeof(object)).ToArray());
if (methodInfo == null)
{
//查找可能存在的泛型方法
methodInfo = typeOfInstance
.GetMethods()
.FirstOrDefault(p => p.Name == methodName
&& p.IsGenericMethod
&& p.GetParameters().Length == values.Length);
}
if (methodInfo == null)
throw new ArgumentException("找不到指定的方法,请检查方法名或者参数数组是否存在匹配");
var paramInfos = methodInfo.GetParameters();
for (var i = 0; i < values.Length; i++)
{
var value = values[i];
var paramInfo = paramInfos.ElementAt(i);
var context = new ValidationContext(paramInfo);
Validator.ValidateValue(value, context, paramInfo.GetCustomAttributes<ValidationAttribute>());
}
}

验证的目标实体:

    public class User
{
[Required] //表示此字段不能为null或空字符串
[StringLength(3)] //表示此字段能接收的最大字符串长度
public string Name { get; set; } [Range(0, 120)] //表示数据字段的最小最大范围
public int Age { get; set; }
}

实体验证:

    User user = new User() { Name = "A,ning", Age = 140 };

    ICollection<ValidationResult> errors = new List<ValidationResult>();

    //如果不关注验证结果, 可不传入 errors 参数, 验证失败将只返回false
if (user.TryValidate(errors))
{
Console.WriteLine("验证通过");
}
else
{
Console.WriteLine("验证失败");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(string.Join(Environment.NewLine, errors.Select(p => p.ErrorMessage)));
}

方法参数验证(支持泛型方法):

public void SayHello<T>([Required][StringLength(3)] T name, [Range(0, 120)] int age)
{
var errors = new List<ValidationResult>();
if (this.TryValidate(nameof(SayHello), new object[] { name, age }, errors))
{
Console.WriteLine("验证通过");
}
else
{
Console.WriteLine("验证失败");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(string.Join(Environment.NewLine, errors.Select(p => p.ErrorMessage)));
}
}

7. 判断Type是否为.NET Framework内置类型

    /// <summary>
/// 判断<see cref="Type"/>是否为用户自定义类型
/// </summary>
/// <param name="type">type</param>
/// <returns>如果为 .NET 内置类型返回false,否则返回true</returns>
public static bool IsCustomType(this Type type)
{
return (type != typeof(object) && Type.GetTypeCode(type) == TypeCode.Object);
}

.NET 实用扩展方法的更多相关文章

  1. ABP源码分析十五:ABP中的实用扩展方法

    类名 扩展的类型 方法名 参数 作用 XmlNodeExtensions XmlNode GetAttributeValueOrNull attributeName Gets an   attribu ...

  2. [Swift通天遁地]五、高级扩展-(7)UIView(视图类型)的各种扩展方法

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...

  3. Visual Studio 实用扩展推荐

    Visual Studio 拥有非常不错的可扩展性,在之前的文章中,我也给大家示范了如何进行编辑器的扩展(详见文末参考资源).在本篇文章中,我将介绍几款非常实用的扩展,从而帮助我们提高开发效率. C# ...

  4. 【开源】OSharp框架解说系列(3):扩展方法

    OSharp是什么? OSharp是个快速开发框架,但不是一个大而全的包罗万象的框架,严格的说,OSharp中什么都没有实现.与其他大而全的框架最大的不同点,就是OSharp只做抽象封装,不做实现.依 ...

  5. 分享.NET系统开发过程中积累的扩展方法

    .NET 3.5提供的扩展方法特性,可以在不修改原类型代码的情况下扩展它的功能.下面分享的这些扩展方法大部分来自于Code Project或是Stackoverflow,.NET为此还有一个专门提供扩 ...

  6. MVC缓存03,扩展方法实现视图缓存

    关于缓存,先前尝试了: ● 在"MVC缓存01,使用控制器缓存或数据层缓存"中,分别在控制器和Data Access Layer实现了缓存 ● 在"MVC缓存02,使用数 ...

  7. .NET开发中经常用到的扩展方法

    整理一下自己经常用到的几个扩展方法,在实际项目中确实好用,节省了不少的工作量. 1  匿名对象转化 在WinForm中,如果涉及较长时间的操作,我们一般会用一个BackgroundWorker来做封装 ...

  8. [转]Visual Studio 实用扩展推荐

    本文转自 http://www.cnblogs.com/stg609/p/3726898.html Visual Studio 拥有非常不错的可扩展性,在之前的文章中,我也给大家示范了如何进行编辑器的 ...

  9. 再不用担心DataRow类型转换和空值了(使用扩展方法解决高频问题)

    在使用DataRow读取数据时,通常会遇到数据可能为Null, 但是又需要转换为如int等其它类型的数据,因此就通常会写这样的代码: if (dr[name] != DBNull.Value & ...

随机推荐

  1. gym 101873

    题还没补完 以下是牢骚:删了 现在只有六个...太恐怖了,我发现四星场我连300人的题都不会啊. C:最短路加一维状态就好了叭..嗯,一开始没看到输出的那句话 那个  "."也要输 ...

  2. ubuntu下nodejs和npm的安装及升级

    ubuntu 下 nodejs 和 npm 的安装及升级 参考:https://segmentfault.com/a/1190000007542620 一:ubuntu下安装 node 和 npm命令 ...

  3. php框架中,try,catch不能用的问题(转载)

    本文转自:http://blog.csdn.net/sangjinchao/article/details/71436557 最近再用laravel框架发现,try catch用了没有效果,依然不能阻 ...

  4. 关于js执行机制的理解

    js是单线程语言.指的是js的所以程序执行通过仅有的这一个主线程来执行. 但是还有辅助线程,包括定时器线程,ajax请求线程和事件线程. js的异步我理解的是: 主线程执行时候,从上到下依次执行,遇到 ...

  5. loadrunner笔记(二):飞机订票系统--客户信息注册

    (一)  几个重要概念说明 集合点:同步虚拟用户,以便同一时间执行任务. 事务:事务是指服务器响应用户请求所用的时间,当然它可以衡量某个操作,如登录所需要的时间,也可以衡量一系列的操作所用的时间,如从 ...

  6. ajax方式提交表单数据并判断当前注册用户是否存在

    项目的目录结构 源代码: regservlet.java package register; import java.io.IOException; import java.io.PrintWrite ...

  7. POJ 3078 - Shuffle'm Up - [模拟题]

    题目链接:http://poj.org/problem?id=3087 Description A common pastime for poker players at a poker table ...

  8. linux学习:【第3篇】远程连接及软件安装

    狂神声明 : 文章均为自己的学习笔记 , 转载一定注明出处 ; 编辑不易 , 防君子不防小人~共勉 ! linux学习:[第3篇]远程连接及软件安装 远程连接 xshell , xftp软件官网 : ...

  9. apache tomcat (catalina)查版本(solaris/unix)

    先进到tomcat的bin目录下(cd /tomcat目录/bin),在执行./version.sh https://blog.csdn.net/vv___/article/details/78653 ...

  10. com.mysql.jdbc.Driver 与 org.gjt.mm.mysql.Driver的区别

    com.mysql.jdbc.Driver的前身是org.gjt.mm.mysql.Driver,现在主要用com.mysql.jdbc.Driver,但为了保持兼容性保留了org.gjt.mm.my ...