C#扩展方法知多少
前言:上篇 序列化效率比拼——谁是最后的赢家Newtonsoft.Json 介绍了下序列化方面的知识。看过Demo的朋友可能注意到了里面就用到过泛型的扩展方法,,本篇打算总结下C#扩展方法的用法。博主打算分三个层面来介绍这个知识点,分别是:.Net内置对象的扩展方法、一般对象的扩展方法、泛型对象的扩展方法。
什么是扩展方法?回答这个问题之前,先看看我们一般情况下方法的调用。类似这样的通用方法你一定写过:
static void Main(string[] args) { string strRes = "2013-09-08 14:12:10"; var dRes = GetDateTime(strRes); } //将字符串转换为日期 public static DateTime GetDateTime(string strDate) { return Convert.ToDateTime(strDate); } //得到非空的字符串 public static string GetNotNullStr(string strRes) { if (strRes == null) return string.Empty; else return strRes; }
或者在项目中有一个类似Utils的工具类,里面有多个Helper,例如StringHelper、XmlHelper等等,每个Helper里面有多个static的通用方法,然后调用的时候就是StringHelper.GetNotNullStr("aa");这样。还有一种普通的用法就是new 一个对象,通过对象去调用类里面的非static方法。反正博主刚开始做项目的时候就是这样写的。后来随着工作经验的累积,博主看到了扩展方法的写法,立马就感觉自己原来的写法太Low了。进入正题。
1、.Net内置对象的扩展方法
比如我们要给string对象加一个扩展方法(注意这个方法不能和调用的Main方法放在同一个类中):
public static string GetNotNullStr(this string strRes) { if (strRes == null) return string.Empty; else return strRes ; }
然后在Main方法里面调用:
static void Main(string[] args) { string strTest = null; var strRes = strTest.GetNotNullStr(); }
简单介绍:public static string GetNotNullStr(this string strRes)其中this string就表示给string对象添加扩展方法。那么在同一个命名空间下面定义的所有的string类型的变量都可以.GetNotNullStr()这样直接调用。strTest.GetNotNullStr();为什么这样调用不用传参数,是因为strTest就是作为参数传入到方法里面的。你可以试试。使用起来就和.Net framework定义的方法一样:
当然除了string,你可以给.Net内置的其他对象加扩展方法,例如给DataGridViewRow的扩展方法:
//DataGridViewRow的扩展方法,将当前选中行转换为对应的对象 public static T ToObject<T>(this DataGridViewRow item) where T:class { var model = item.DataBoundItem as T; if (model != null) return model; var dr = item.DataBoundItem as System.Data.DataRowView; model = (T)typeof(T).GetConstructor(new System.Type[] { }).Invoke(new object[] { });//反射得到泛型类的实体 PropertyInfo[] pro = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public); Type type = model.GetType(); foreach (PropertyInfo propertyInfo in pro) { if (Convert.IsDBNull(dr[propertyInfo.Name])) { continue; } if (!string.IsNullOrEmpty(Convert.ToString(dr[propertyInfo.Name]))) { var propertytype = propertyInfo.PropertyType; } } return model; }
View Code这样看上去就像在扩展.Net Framework。有没有感觉有点高大上~
2、一般对象的扩展方法
和Framework内置对象一样,自定义的对象也可以增加扩展方法。直接上示例代码:
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/70026.html