c#如何扩展类型的内置方法

c#3.0(VS2008)支持在任何类型上扩展生成自定义的方法。比如说想在string类型的对象里面多一个ToInt32(),来方便的将字符转换成整形。

在实现的过程中的关键字为static和this

下面我们来做一个在string类型中新建一个ToInt32的自定义方法

ContractedBlock.gif ExpandedBlockStart.gif View Code
    public static class Extension//必须先声明一个静态类,类名随意
{
public static int ToInt32(this string In)//扩建的方法必须是静态方法,参数里面必须含有this关键字,this关键字后面的类型为需要扩展的类型
{
return Convert.ToInt32(In);
}
}

那么在使用string的对象的时候,会多出一个ToInt32的方法

ContractedBlock.gif ExpandedBlockStart.gif View Code
static void Main(string[] args)
{
string a = "1";
int b = a.ToInt32();
Console.ReadLine();
}

既然可以扩展.net的内置类型,那能不能扩展自定义类型呢。

ContractedBlock.gif ExpandedBlockStart.gif View Code
    public class A//先定义A类
{
}

public static class Extension//必须先声明一个静态类,类名随意
{
public static int ToInt32(this string In)//扩建的方法必须是静态方法,参数里面必须含有this关键字,this关键字后面的类型
{
return Convert.ToInt32(In);
}
//为A新增一个ExtensionMethod方法
public static string ExtensionMethod(this A a)//扩建的方法必须是静态方法,参数里面必须含有this关键字,this关键字后面的类型
{
return "this is extension method";
}
}

在使用A的对象的时候,会多出一个ExtensionMethod方法

ContractedBlock.gif ExpandedBlockStart.gif View Code
static void Main(string[] args)
{
string a = "1";
int b = a.ToInt32();
A c
= new A();
string d = c.ExtensionMethod();
Console.ReadLine();
}

C#3.0的这个新特性意味着我们可以肆无忌惮的扩展我们想要扩展的类型,即便这个类型是从别的地方引用过来的。

转载于:https://www.cnblogs.com/WindBlog/archive/2011/07/29/2120655.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值