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

下面这个例子是用来扩展string, 也可以是其他对象。请大家注意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());  
        }  
    }  
}  

 

posted @ 2014-04-18 14:08  邹邹  Views(331)  Comments(0)    收藏  举报