wfdoublext 发表于 2013-1-26 12:58:16

C#扩展对象的方法,this关键字


[*]namespace ConsoleApplication2  
[*]{  
[*]    class Program  
[*]    {  
[*]        static void Main(string[] args)  
[*]        {  
[*]            // 测试代码  
[*]            string a = "100";  
[*]            a.Show();  
[*]            a = "-500";  
[*]            a.Show();  
[*]            a = "0";  
[*]            a.Show();  
[*]            a = "abcd";  
[*]            a.Show();  
[*]        }  
[*]    }  
[*]  
[*]    //必须将扩展写在静态类中。  
[*]    static class MyExtensions  
[*]    {  
[*]        // 为string对象添加转换为整数的扩展方法  
[*]        public static int ToInt32(this string s)  
[*]        {  
[*]            int ret = -1;  
[*]            int.TryParse(s, out ret);  
[*]            return ret;  
[*]        }  
[*]  
[*]        // 为string对象添加用来显示的扩展方法  
[*]        public static void Show(this string s)  
[*]        {  
[*]            // 调用转换为int扩展方法  
[*]            int b = s.ToInt32();  
[*]            Console.WriteLine(b.ToString());  
[*]        }  
[*]    }  
[*]}  
页: [1]
查看完整版本: C#扩展对象的方法,this关键字