现在的位置: 首页 > 综合 > 正文

扩展方法必须在非泛型静态类中定义

2013年01月23日 ⁄ 综合 ⁄ 共 859字 ⁄ 字号 评论关闭

http://blog.sina.com.cn/s/blog_a5193ed401016mvb.html

 

扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。

扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。 它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。

扩展方法的要求如下:

1  第一个参数是要扩展或者要操作的类型,这称为"被扩展的类型"

2  为了指定扩展方法,要在被扩展的类型名称前面附加this修饰符

3  要将方法作为一个扩展方法来访问,要用using指令导入扩展类型的命名空间,或者使扩展类型和调用代码在同一个命名空间中.

    1. //扩展方法必须在非泛型静态类中定义  
    2.    public static class qzwtest  
    3.    {  
    4.        //扩展方法  
    5.        public static string[] qzw(this string str)  
    6.        {  
    7.            return str.Split(new char[] { ' '',' });  
    8.        }  
    9.    }  
    10.   
    11.    class Program  
    12.    {  
    13.        static int Main()  
    14.        {  
    15.   
    16.            string testStr = "钱卓文 is 喵喵,贤静";  
    17.            //调用扩展方法  
    18.            string[] testArray = testStr.qzw();  
    19.            foreach (string s in testArray)  
    20.            {  
    21.                Console.WriteLine(s);  
    22.            }  
    23.   
    24.            Console.ReadKey();  
    25.            return 0;  
    26.        }  
    27.    

抱歉!评论已关闭.