- 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());
- }
- }
- }
C#扩展对象的方法,this关键字
最新推荐文章于 2025-06-29 19:58:48 发布
本文介绍了如何在C#中通过扩展方法为字符串对象添加转换为整数的功能,并展示了如何使用这个扩展方法进行简单的数据处理和输出。
1535

被折叠的 条评论
为什么被折叠?



