ITeye博客

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

wfdoublext · 2011-06-15 10:58 · .net · 编程语言 · C · C++ · C# · Markdown

  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. static class MyExtensions
  20. {
  21. // 为string对象添加转换为整数的扩展方法
  22. public static int ToInt32(this string s)
  23. {
  24. int ret = -1;
  25. int.TryParse(s, out ret);
  26. return ret;
  27. }
  28. // 为string对象添加用来显示的扩展方法
  29. public static void Show(this string s)
  30. {
  31. // 调用转换为int扩展方法
  32. int b = s.ToInt32();
  33. Console.WriteLine(b.ToString());
  34. }
  35. }
  36. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。