扩展方法举例说明

C#中可以定义 扩展方法,还可以 为集合做扩展方法

示例如下:

扩展方法
using System;
using System.Collections.Generic; 

using MySpace;  // 注意:引入扩展方法的空间

namespace Con_1
{
     class Program
    {
         static  void Main( string[] args)
        {
             string str =  " {0}先生。 ".With( " XuGang ");
            Console.WriteLine( " 您好! " + str);

             // 2调用集合的扩展方法
            str.ShowItems< char>();
        }
    }
}

namespace MySpace
{
     // 扩展方法必须在非泛型静态类中定义
     public  static  class MyMethods
    {
         // 注意:第一个参数使用“this”获得当前对象
         public  static  string With( this  string _context,  params  string[] _args)
        {
             return  string.Format(_context,_args);
        }


         // 2为集合做扩展方法
         public  static  void ShowItems<T>( this IEnumerable<T> _al)
        {
             foreach (var item  in _al)
            {
                Console.WriteLine(item);
            }
        }
    }
}

注意:

 

1  C# 只支持扩展方法,不支持扩展属性、扩展事件等;

2  方法名无限制,第一个参数必须带 this ;

3  扩展方法的命名空间可以使用 namespace System ,但不推荐;

4  定义扩展方法的类是静态类;

 

 

在使用this 参数扩展了方法之后,该程序集会在编译的时候会在对应静态类上加上类似以下的东西。以便于调用的时候方便找到。
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)] 
public  sealed  class ExtensionAttribute : Attribute 

  ......
}


 

 

MSIL 中,自动添加了如下的代码:
.custom instance  void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = (  01  00  00  00 ) 

 

可以看出,在运行时是需要引用 System.Core.dll。

例2
namespace TestExtensionMethods
{
   //①必须建一个静态类(任意有效命名),用来包含要添加的扩展方法

   public static class MyExtensions
   {
       //②要添加的扩展方法必须为一个静态方法
       public static int MyNewMethod(this string s)
       {
           return s.Length;
       }
   }

   //测试扩展方法类
   class Program
   {
       static voidMain(string[] args)
       {
           string str = "Hello Extension Methods in C# 3.0";
           Console.WriteLine(str);
           //③调用扩展方法,必须用对象来调用
          int len = str.MyNewMethod();
           Console.WriteLine(len);
           Console.ReadKey();
       }
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值