扩展方法的使用

示例如下:

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

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

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

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

        }
    }
}

namespace class1
{
    //扩展方法必须在非泛型静态类中定义
    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  定义扩展方法的类是静态类;

5扩展方法中(如果文件中没有原来没有这个方法,这个方法是在后来加上去的话那么在调用的时候方法的样子就会有一个垂直的箭头,如果原来有的话这个 方法就会有一个扩展)

如图

 

public static string cc()
{
return "adfadsf";
}
public static string cc(this string name)
{
return name;
}

public static string GetChineseSpell(this string s)
{
return null;//请自行完成
}

 

posted @ 2014-04-23 14:18  醉孟子  阅读(241)  评论(0编辑  收藏  举报