分享.NET系统开发过程中积累的扩展方法
2015-07-21 09:00
387 查看
.NET3.5提供的扩展方法特性,可以在不修改原类型代码的情况下扩展它的功能。下面分享的这些扩展方法大部分来自于CodeProject或是Stackoverflow,.NET为此还有一个专门提供扩展方法的网站(extensionMethod)。涵盖类型转换,字符串处理,时间转化,集合操作等多个方面的扩展。
扩展方法的源代码定义只有一行,源代码如下:
当我想对一个集合中的每个元素执行相同的操作时,常常会借助于此方法实现。
类似这样的操作,下面的方法是取2个值的最大值。
1TolerantCast匿名类型转换
这个需求来源于界面中使用BackgroundWorker,为了给DoWork传递多个参数,又不想定义一个类型来完成,于是我会用到TolerantCast方法。参考如下的代码://创建匿名类型 varparm=new{Bucket=bucket,AuxiliaryAccIsCheck=chbAuxiliaryAcc.Checked,AllAccountIsCheck=chbAllAccount.Checked}; backgroundWorker.RunWorkerAsync(parm); privatevoidbackgroundWorker_DoWork(objectsender,DoWorkEventArgse) { //解析转换匿名类型 varparm=e.Argument.TolerantCast(new{Bucket=newRelationPredicateBucket(),AuxiliaryAccIsCheck=false,AllAccountIsCheck=false});
2ForEach集合操作
这个方法的定义很简单但也很实用,它的使用方法如下:varbuttons=GetListOfButtons()asIEnumerable<Button>; buttons.ForEach(b=>b.Click());
扩展方法的源代码定义只有一行,源代码如下:
publicstaticvoidForEach<T>(thisIEnumerable<T>@enum,Action<T>mapFunction) { foreach(varitemin@enum)mapFunction(item); }
当我想对一个集合中的每个元素执行相同的操作时,常常会借助于此方法实现。
3Capitalize字符串首字母大写
直接对字符串操作,将字符串的首字母改成大写,源代码参考如下:publicstaticstringCapitalize(thisstringword)
{
if(word.Length<=1)
returnword;returnword[0].ToString().ToUpper()+word.Substring(1);
}
4ToDataTable强类型对象集合转化为DataTable
开发中经常会遇到将List<Entity>转化为DataTable,或是反之将DataTable转化为List<Entity>,stackoverflow上有很多这个需求的代码,参考下面的程序代码:publicstaticDataTableToDataTable<T>(thisIEnumerable<T>varlist)
{
DataTabledtReturn=newDataTable();//columnnames
PropertyInfo[]oProps=null;if(varlist==null)returndtReturn;foreach(Trecinvarlist)
{
//Usereflectiontogetpropertynames,tocreatetable,Onlyfirsttime,otherswillfollow
if(oProps==null)
{
oProps=((Type)rec.GetType()).GetProperties();
foreach(PropertyInfopiinoProps)
{
TypecolType=pi.PropertyType;if((colType.IsGenericType)&&(colType.GetGenericTypeDefinition()==typeof(Nullable<>)))
{
colType=colType.GetGenericArguments()[0];
}dtReturn.Columns.Add(newDataColumn(pi.Name,colType));
}
}DataRowdr=dtReturn.NewRow();foreach(PropertyInfopiinoProps)
{
dr[pi.Name]=pi.GetValue(rec,null)==null?DBNull.Value:pi.GetValue
(rec,null);
}dtReturn.Rows.Add(dr);
}
returndtReturn;
}
5SetAllValues给数组中的每个元素赋值
实现给数组中的每个元素赋相同的值。publicstaticT[]SetAllValues<T>(thisT[]array,Tvalue)
{
for(inti=0;i<array.Length;i++)
{
array[i]=value;
}returnarray;
}
6ToXml序列化对象为Xml格式
可以将一个对象序列化为Xml格式的字符串,保存对象的状态。publicstaticstringToXml<T>(thisTo)whereT:new()
{
stringretVal;
using(varms=newMemoryStream())
{
varxs=newXmlSerializer(typeof(T));
xs.Serialize(ms,o);
ms.Flush();
ms.Position=0;
varsr=newStreamReader(ms);
retVal=sr.ReadToEnd();
}
returnretVal;
}
7Between值范围比较
可以判断一个值是否落在区间范围值中。publicstaticboolBetween<T>(thisTme,Tlower,Tupper)whereT:IComparable<T>
{
returnme.CompareTo(lower)>=0&&me.CompareTo(upper)<0;
}
类似这样的操作,下面的方法是取2个值的最大值。
publicstaticTMax<T>(Tvalue1,Tvalue2)whereT:IComparable
{
returnvalue1.CompareTo(value2)>0?value1:value2;
}
8StartDateDueDate开始值或末值
业务系统中常常会用到时间比较,如果系统是用DateTime.Now变量与DateTime.Today来作比较,前者总是大于后者的,为此需要做一个简单转化,根据需要将值转化为开始值或末值,也就是0点0分0秒,或是23时59分59秒。publicstaticDateTimeConverToStartDate(thisDateTimedateTime)
{
returnnewDateTime(dateTime.Year,dateTime.Month,dateTime.Day,0,0,0);
}publicstaticDateTimeConverToDueDate(thisDateTimedateTime)
{
returnnewDateTime(dateTime.Year,dateTime.Month,dateTime.Day,23,59,59);
}
9FirstDayLastDay月的第一天或是最后一天
publicstaticDateTimeFirst(thisDateTimecurrent)
{
DateTimefirst=current.AddDays(1-current.Day);
returnfirst;
}
publicstaticDateTimeLast(thisDateTimecurrent)
{
intdaysInMonth=DateTime.DaysInMonth(current.Year,current.Month);DateTimelast=current.First().AddDays(daysInMonth-1);
returnlast;
}
10Percent百分比值
计算前一个数值占后一个数值的百分比,常用于统计方面。publicstaticdecimalPercentOf(thisdoubleposition,inttotal)
{
decimalresult=0;
if(position>0&&total>0)
result=(decimal)((decimal)position/(decimal)total*100);
returnresult;
}转载自:http://www.cnblogs.com/JamesLi2015/p/4663292.html
相关文章推荐
- [leetcode-236]Lowest Common Ancestor of a Binary Tree(C语言)236
- Genesis自动登录方法(免输入用户名和密码)
- 美国航天局的十大编码戒律(转)
- 6. JavaSE-面向对象简介
- 专题十一 开源项目的真相
- 数据类型
- Android中jni使用
- PHP实现无限极分类
- Kickstart自动化安装系统
- 如果生活可以说到做到,谁都是任何人
- 【SpringMVC框架】小结+视图解析器配置前缀和后缀
- 专题十 面试基本应对机制
- 自动交互之sshpass用法
- iteratorTag.jsp和fragmentTag.jsp报错的处理javax/el/ELResolver
- XCode: 如何添加自定义代码片段
- java中ArrayList的使用
- Datatable To List<Entity>
- Eclipse for Mac 常用快捷键
- 图像局部与部分分割--opencv
- 如何自学 Android 编程?(励志)