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

涵盖类型转换,字符串处理,时间转化,集合操作等多个方面的扩展。

1  TolerantCast 匿名类型转换

这个需求来源于界面中使用BackgroundWorker,为了给DoWork传递多个参数,又不想定义一个类型来完成,于是我会用到TolerantCast方法。参考如下的代码:

//创建匿名类型
var parm = new { Bucket = bucket, AuxiliaryAccIsCheck = chbAuxiliaryAcc.Checked, AllAccountIsCheck = chbAllAccount.Checked };
backgroundWorker.RunWorkerAsync(parm); private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//解析转换匿名类型
var parm = e.Argument.TolerantCast(new { Bucket = new RelationPredicateBucket(), AuxiliaryAccIsCheck = false, AllAccountIsCheck = false });

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

2  ForEach 集合操作

这个方法的定义很简单但也很实用,它的使用方法如下:

var buttons = GetListOfButtons() as IEnumerable<Button>;
buttons.ForEach(b => b.Click());

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

扩展方法的源代码定义只有一行,源代码如下:

public static void ForEach<T>(this IEnumerable<T> @enum, Action<T> mapFunction)
{
foreach (var item in @enum) mapFunction(item);
}
 

当我想对一个集合中的每个元素执行相同的操作时,常常会借助于此方法实现。

3 Capitalize 字符串首字母大写

直接对字符串操作,将字符串的首字母改成大写,源代码参考如下:

public static string Capitalize(this string word)
{
if (word.Length <= 1)
return word; return word[0].ToString().ToUpper() + word.Substring(1);
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

4  ToDataTable 强类型对象集合转化为DataTable

开发中经常会遇到将List<Entity>转化为DataTable,或是反之将DataTable转化为List<Entity>,stackoverflow上有很多这个需求的代码,参考下面的程序代码:

 public static DataTable ToDataTable<T>(this IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable(); // column names
PropertyInfo[] oProps = null; if (varlist == null) return dtReturn; foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others will follow
if (oProps == null)
{
oProps = ((Type) rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof (Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
} dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
} DataRow dr = dtReturn.NewRow(); foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
(rec, null);
} dtReturn.Rows.Add(dr);
}
return dtReturn;
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

5  SetAllValues 给数组中的每个元素赋值

实现给数组中的每个元素赋相同的值。

public static T[] SetAllValues<T>(this T[] array, T value)
{
for (int i = 0; i < array.Length; i++)
{
array[i] = value;
} return array;
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

6 ToXml 序列化对象为Xml格式

可以将一个对象序列化为Xml格式的字符串,保存对象的状态。

public static string ToXml<T>(this T o) where T : new()
{
string retVal;
using (var ms = new MemoryStream())
{
var xs = new XmlSerializer(typeof (T));
xs.Serialize(ms, o);
ms.Flush();
ms.Position = 0;
var sr = new StreamReader(ms);
retVal = sr.ReadToEnd();
}
return retVal;
}

7  Between 值范围比较

可以判断一个值是否落在区间范围值中。

public static bool Between<T>(this T me, T lower, T upper) where T : IComparable<T>
{
return me.CompareTo(lower) >= 0 && me.CompareTo(upper) < 0;
}

类似这样的操作,下面的方法是取2个值的最大值。

public static T Max<T>(T value1, T value2) where T : IComparable
{
return value1.CompareTo(value2) > 0 ? value1 : value2;
}
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

8  StartDate DueDate 开始值或末值

业务系统中常常会用到时间比较,如果系统是用DateTime.Now变量与DateTime.Today来作比较,前者总是大于后者的,为此需要做一个简单转化,根据需要将值转化为开始值或末值,也就是0点0分0秒,或是23时59分59秒。

public static DateTime ConverToStartDate(this DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0);
} public static DateTime ConverToDueDate(this DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 23, 59, 59);
}
 

9 First Day Last Day 月的第一天或是最后一天

public static DateTime First(this DateTime current)
{
DateTime first = current.AddDays(1 - current.Day);
return first;
}
public static DateTime Last(this DateTime current)
{
int daysInMonth = DateTime.DaysInMonth(current.Year, current.Month); DateTime last = current.First().AddDays(daysInMonth - 1);
return last;
}


 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

10 Percent 百分比值

计算前一个数值占后一个数值的百分比,常用于统计方面。

public static decimal PercentOf(this double position, int total)
{
decimal result = 0;
if (position > 0 && total > 0)
result=(decimal)((decimal)position / (decimal)total * 100);
return result;
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

扩展方法源代码下载:http://files.cnblogs.com/files/JamesLi2015/ExtensionMethod.zip

分享.NET系统开发过程中积累的扩展方法的更多相关文章

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

    分享.NET系统开发过程中积累的扩展方法   .NET 3.5提供的扩展方法特性,可以在不修改原类型代码的情况下扩展它的功能.下面分享的这些扩展方法大部分来自于Code Project或是Stacko ...

  2. ASP.NET Core中,UseDeveloperExceptionPage扩展方法会吃掉异常

    在ASP.NET Core中Startup类的Configure方法中,有一个扩展方法叫UseDeveloperExceptionPage,如下所示: // This method gets call ...

  3. C#中this在扩展方法的应用

    给类添加扩展方法 1.定义一个类Service public class Service { private string _name; public string Name { get { retu ...

  4. ABP框架源码中的Linq扩展方法

    文件目录:aspnetboilerplate-dev\aspnetboilerplate-dev\src\Abp\Collections\Extensions\EnumerableExtensions ...

  5. (转)嵌入式linux系统开发过程中遇到的——volatile

    原文地址:http://blog.csdn.net/HumorRat/article/details/5631023 对于不同的计算机体系结构,设备可能是端口映射,也可能是内存映射的.如果系统结构支持 ...

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

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

  7. Yii框架中安装srbac扩展方法

    首先,下载srbac_1.3beta.zip文件和对应的blog-srbac_1.2_r228.zip 问什么要下载第二个文件,后面就知道了. 按照手册进行配置: 解压缩srbac_1.3beta.z ...

  8. 【EF学习笔记11】----------查询中常用的扩展方法

    先来看一下我们的表结构: 首先毫无疑问的要创建我们的上下文对象: using (var db = new Entities()) { //执行操作 } Average 平均值: //查询平均分 Con ...

  9. FSBPM 开发过程中一些提醒备注信息(供参考)

    ------智能OA系统开发过程中 前端开发前端 搜索查询的配置 运算操作符:   like         equals     共两种筛选数据方式. html标签上配置一下eg: <inpu ...

随机推荐

  1. CentOS访问Windows共享文件夹的方法

    CentOS访问Windows共享文件夹的方法 1 在地址栏中输入下面内容: smb://Windows IP/Share folder name,smb为Server Message Block协议 ...

  2. 近期C#项目中总结

    1. 读写文件操作 using (file = new System.IO.StreamReader(inputfile)) { using (outfile = new System.IO.Stre ...

  3. 数据库软件dbForge Studio for MySQL更新至v.6.1

    本文转自:慧都控件网 说到MariaDB,这个数据库算是MySQL的一个分支.现在非常的流行,很多地方都能看到它的身影.MariaDB作为一种新的数据库管理系统,在短时间内获得如此高的关注度.这也是D ...

  4. viojs1908无线网路发射器选址

      描述 随着智能手机的日益普及,人们对无线网的需求日益增大.某城市决定对城市内的公共场所覆盖无线网. 假设该城市的布局为由严格平行的 129 条东西向街道和 129 条南北向街道所形成的网格状,并且 ...

  5. html入门问题_2016-10-29

    在mac机器上,用Safari打开html文件 1. 如果html里有中文,则在<head><meta http-equiv="Content-Type" con ...

  6. uva 11174 Stand in a Line

    // uva 11174 Stand in a Line // // 题目大意: // // 村子有n个村民,有多少种方法,使村民排成一条线 // 使得没有人站在他父亲的前面. // // 解题思路: ...

  7. 【转】COM技术内幕(笔记)

    COM技术内幕(笔记) COM--到底是什么?--COM标准的要点介绍,它被设计用来解决什么问题?基本元素的定义--COM术语以及这些术语的含义.使用和处理COM对象--如何创建.使用和销毁COM对象 ...

  8. windows配置php开发环境

    1.安装xampp. xampp集成了php.prel.mysql.apache等网站工具,安装超简单,本身也超级好用.点击下载xampp 2.讲xmapp中的php配置到环境变量 比如我的xampp ...

  9. 《理解 ES6》阅读整理:函数(Functions)(八)Tail Call Optimization

    尾调用优化(Tail Call Optimization) 尾调用是指函数的最后一条语句是函数调用,比如下面的代码: function doSomething() { return doSomethi ...

  10. How and Where Concurrent Asynchronous I/O with ASP.NET Web API 对异步编程分析的非常的好

    How and Where Concurrent Asynchronous I/O with ASP.NET Web API http://www.tugberkugurlu.com/archive/ ...