C#扩展对象的方法,this关键字
wfdoublext
· 2011-06-15 10:58 · .net · 编程语言 · C · C++ · C#
· Markdown
- 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());
- }
- }
- }