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

本文介绍了如何在C#中通过扩展方法为字符串对象添加转换为整数的功能,并展示了如何使用这个扩展方法进行简单的数据处理和输出。

  1. namespace ConsoleApplication2  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             // 测试代码  
  8.             string a = "100";  
  9.             a.Show();  
  10.             a = "-500";  
  11.             a.Show();  
  12.             a = "0";  
  13.             a.Show();  
  14.             a = "abcd";  
  15.             a.Show();  
  16.         }  
  17.     }  
  18.   
  19.     //必须将扩展写在静态类中。  
  20.     static class MyExtensions  
  21.     {  
  22.         // 为string对象添加转换为整数的扩展方法  
  23.         public static int ToInt32(this string s)  
  24.         {  
  25.             int ret = -1;  
  26.             int.TryParse(s, out ret);  
  27.             return ret;  
  28.         }  
  29.   
  30.         // 为string对象添加用来显示的扩展方法  
  31.         public static void Show(this string s)  
  32.         {  
  33.             // 调用转换为int扩展方法  
  34.             int b = s.ToInt32();  
  35.             Console.WriteLine(b.ToString());  
  36.         }  
  37.     }  
  38. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值