c#扩展方法的理解(一:初识)
扩展方法是静态方法,是类的一部分,但是实际上没有放在类的源代码中。
扩展方法所在的类也必须被声明为static
C#只支持扩展方法,不支持扩展属性、扩展事件等。
扩展方法的第一个参数是要扩展的类型,放在this关键字的后面,告诉编译期这个方法是Money类型的一部分。
在扩展方法中,可以访问扩展类型的所有公共方法和属性。
“扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。”
这是msdn上说的,也就是你可以对String,Int,DataRow,DataTable等这些类型的基础上增加一个或多个方法,使用时不需要去修改或编译类型本身的代码。
先做个例子吧,以String为例,需要在字符串类型中加一个从字符串转为数值的功能。
以往我们可能是这样做的,会专门写一个方法做过转换
public static int StrToInt(string s){ int id; int.TryParse(s, out id);//这里当转换失败时返回的id为0 return id;} |
调用就使用
string s = "abc";int i = StrToInt(s); |
若是String类型有一个名为ToInt()(从字符串转为数值)的方法,就可以这样调用了
string s = "abc";int i = s.ToInt(); |
这样看起来是不是更好,下面来看看具体怎么实现吧
第一步:
我先创建一个解决方案,一个web应用程序(webtest)及一个类库(W.Common)

在webtest项目添加引用W.Common项目

第二步:在类库中新建一个名为EString.cs类
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace W.Common{ public static class EString { /// <summary> /// 将字符串转换为Int /// </summary> /// <param name="t"></param> /// <returns>当转换失败时返回0</returns> public static int ToInt(this string t) { int id; int.TryParse(t, out id);//这里当转换失败时返回的id为0 return id; } }} |
看了上面的代码了吧,扩展方法规定类必须是一个静态类,EString是一个静态类,里面包含的所有方法都必须是静态方法。
msdn是这样规定扩展方法的:“扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。 它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。”
EString里有一个ToInt的静态方法,他接收一个自身参数this,类型为string,this string必须在方法参数的第一个位置。
这句话什么意思,即你需要对string扩展一个ToInt方法,this是string实例化后的对象,这可能说的不太清楚,我的表述能力能弱,不要见怪呀。。。通俗的说就是,扩展方法跟静态类的名称无关,只需要在一个静态类里面定义一个静态方法,第一个参数必须this string开头。
如果需要你要对DateTime类型扩展方法名为IsRange(判断是否在此时间范围内),代码如下:
/// <summary> /// 此时间是否在此范围内 -1:小于开始时间 0:在开始与结束时间范围内 1:已超出结束时间 /// </summary> /// <param name="t"></param> /// <param name="startTime"></param> /// <param name="endTime"></param> /// <returns></returns> public static int IsRange(this DateTime t, DateTime startTime, DateTime endTime) { if (((startTime - t).TotalSeconds > 0)) { return -1; } if (((endTime - t).TotalSeconds < 0)) { return 1; } return 0; } |
这里的扩展方法是用this DateTime打头,那么就可以这样调用
time.IsRange(t1,t2);//判断时间time是否在t1到t2的范围内 |
当前代码在使用扩展方法前需要先引用命名空间
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using W.Common;//这里引用扩展方法所在的命名空间namespace webtest{ public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { use1(); Response.Write("<br />"); use2(); } /// <summary> /// 没有用扩展方法 /// </summary> private void use1() { string s = "abc"; int i = StrToInt(s); Response.Write("没有用扩展方法:" + i); } /// <summary> /// 使用扩展方法 /// </summary> private void use2() { string s = "2012"; int i = s.ToInt(); Response.Write("使用扩展方法:" + i); } public static int StrToInt(string s) { int id; int.TryParse(s, out id);//这里当转换失败时返回的id为0 return id; } }}
|
第二个案例:——————————————————————————————————————
class Program
{
static void Main(string[] args)
{
Money cash = new Money();
cash.Amount = 40M;
cash.AddToAmount(10M);
Console.WriteLine("cash.ToString() returns: " + cash.ToString());
Console.ReadLine();
}
}
public class Money
{
private decimal amount;
public decimal Amount
{
get
{
return amount;
}
set
{
amount = value;
}
}
public override string ToString()
{
return "$" + Amount.ToString();
}
}
public static class MoneyExtension
{
public static void AddToAmount(this Money money, decimal amountToAdd)
{
money.Amount += amountToAdd;
}
}
c#扩展方法的理解(一:初识)的更多相关文章
- c# 扩展方法初见理解
个人理解扩展方法是对某些类在不改变源码的基础上添加其他的方法.扩展方法必须是在非泛型的静态类里定义,且第一个参数是要使用this 指定需要扩展的类型. class Program { static v ...
- 关于.NET中迭代器的实现以及集合扩展方法的理解
在C#中所有的数据结构类型都实现IEnumerable或IEnumerable<T>接口(实现迭代器模式),可以实现对集合遍历(集合元素顺序访问).换句话可以这么说,只要实现上面这两个接口 ...
- c#扩展方法的理解(二:接口)
namespace ExtensionInterfaceMethod { class Program { static void Main(string[] args) { //使用接口变量来调用扩展 ...
- C#扩展方法的理解
“扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型.” 这是msdn上说的,也就是你可以对String,Int,DataRow,DataTable等这些 ...
- C#扩展方法的理解 (转)
“扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型.” 这是msdn上说的,也就是你可以对String,Int,DataRow,DataTable等这些 ...
- C# 五、谈扩展方法的理解
http://www.cnblogs.com/zhaopei/p/5678842.html
- C#中的反射和扩展方法的运用
前段时间做了一个练手的小项目,采用的是三层架构,也就是Models,IDAL,DAL,BLL 和 Web , 在DAL层中各个类中有一个方法比较常用,那就是 RowToClass ,顾名思义,也就是将 ...
- C#扩展方法学习
扩展方法的本质是什么,详细见此文 C#扩展方法,爱你在心口难开 重点如下:扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型.扩展方法是一种特殊的静态方法 ...
- 初识C#扩展方法
1)扩展方法是什么? 扩展方法可以在不修改原有类的代码前提下,给类“增加”一个方法.扩展方法虽然属于静态方法,但调用的语法却和对象调用类似.直接用一个例子来演示扩展方法. 1.准备实体类 public ...
随机推荐
- <c:if>条件判断 和 取值做乘法运算
http://www.yiibai.com/jstl/jstl_core_if_tag.html <td> ${log.etdhHandleTime }<span> < ...
- 【python cookbook】【数据结构与算法】20.将多个映射合并为单个映射
问题:在逻辑上将多个字典或映射合并为一个单独的映射结构,以此执行某些特定的操作,比如查找值或者检查键是否存在 解决方案:利用collections模块中的ChainMap类 ChainMap可接受多个 ...
- jstl简介
JavaServer Page Standard Tag Library是一个有用的JSP标签的集合,它封装了许多JSP应用程序通用的核心功能. JSTL支持常见的,结构性任务,如迭代和条件,标签为操 ...
- Extended Data Type Properties [AX 2012]
Extended Data Type Properties [AX 2012] This topic has not yet been rated - Rate this topic Updated: ...
- sqlite3把字段为int32(用c++的time(nullptr)获取的)的秒数显示为年月日时分秒
select id, type, msg, datetime(updateTime, 'unixepoch', 'localtime') from ServerLog
- Word and MediaElement
function jmc_new_lib(){// Because we still want the script to load but not the styleswp_enqueue_scri ...
- 查看mysql的状态
实时查看mysql状态连接数 查询数 etc mysqladmin -uroot -p '' -h status -i 1
- python: hashlib 加密模块
加密模块hashlib import hashlib m=hashlib.md5() m.update(b'hello') print(m.hexdigest()) #十六进制加密 m.update( ...
- quick lua 3.3常用方法和学习技巧之functions.lua目录
1.functions.lua (framework->functions.lua) 提供一组常用函数,以及对 Lua 标准库的扩展 1.printf 2.checknumber checkin ...
- SortedDictionary和SortedList
使用上两者的接口都类似字典,并且SortedList的比如Find,FindIndex,RemoveAll常用方法都没提供. 数据结构上二者差异比较大,SortedList查找数据极快,但添加新元素, ...