Visual Studio Orcas之扩展方法小试牛刀

VisualStudio Codename"Orcas"有一个新特性是扩展方法(Extender Method).

首先来好好理解一下什么是扩展方法:从字面上看,首先它属于方法的范畴,但为什么前面有一个扩展呢,可以简单的这样理解"就是新增加的"意思.也就是对于.NET框架下的FCL,微软的工程师已经为我们开发了一些通用的方法,直接调用就可以了,这在给我们带来方便的同时,也极大的限制了FLC类的灵活性,除了继承,我想不出更好的扩展类的方法,可能就是由于这一点,在oracs中引入了扩展方法这一特性。自然是为了更好的解决上面的问题,当然关于扩展方法如何促进LINQ的应用,你可以找LINQ的一些资料去学习一下。

知道了什么是扩展方法,下面来看一下,如何定义或者叫实现扩展方法(仅限于C#3.0)。第一就是要定义一个静态类(不能够被实例化,只能包含静态成员)。第二就是要在该静态类中加入一个静态方法(扩展方法),第三就是一定要将静态方法的第一个参数的类型前用this关键字。第一个参数就是该方法依托的类型(或者说该方法要扩展的类型),当然,扩展方法,还可以有其它的参数,但只能放在第一个特殊的参数之后)。

下面来看一个具体实现的例子(当然很简单),具体的扩展和应用场合的选择要靠大家了。

在该类库中定义扩展方法,如果你的扩展方法的定义和测试扩展方法分别定义在不同的项目中,那么要将静态类和静态方法都要声明成public。
/* function description:display how to use extend method which is embeded
* as a new function character in the next version of
* visual studio codename 'oracs'
* author:haohai fu
* Date:2007-6-14
* Version:1.0
* Details:Make sure that you must define a new public static class in a namespace
* and define a static method as Extender,of which the first parameter must be add
* this key word before the type.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassLibrary1
{
public static class Class1
{
public static string getDate(this string s,string append)
{
return s + append;
}
}
}


这是是测试项目。
/* function description:this is an application entry.display how to use extend method which is embeded
* as a new function character in the next version of
* visual studio codename 'oracs'
* author:haohai fu
* Date:2007-6-14
* Version:1.0
* Details:Please pay attention to how to call the extender method.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
//using ConsoleApplication1;
using ClassLibrary1;//通过添加引用,选择项目选项卡(为什么不选择第一个选项卡,有兴趣的读者可以找微软的软件项目架构的书来看看)
class Program
{
static void Main(string[] args)
{
Console.WriteLine ("Please input four number:");
string year = Console.ReadLine();
Console.WriteLine("Please input a number between 1 and 12:");
string month = Console.ReadLine();
Console.WriteLine("Please input a munber between 1 and 31:");
string day = Console.ReadLine();
Console.WriteLine(year.getDate("nian").getDate(month + "yue").getDate(day + "ri"));
Console.ReadLine();
}
}
}

输出的结果是这样的(虚拟机环境,不支持中文):

Please input four number:
2007
Please input a number between 1 and 12:
6
Please input a munber between 1 and 31:
14
2007nian6yue14ri

最后特别要强调的是扩展方法的调用,大家可以参看上面的代码来体验其灵活性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值