---
title: " C#扩展对象的方法，this关键字"
author: "wfdoublext"
date: "2011-06-15T10:58:57Z"
tags: ["C", "C#", "C++"]
categories: ["编程语言"]
slug: "c-this"
draft: false
lastmod: "2011-06-15T10:58:57Z"
id: 1090157
url: "https://skyofdawn.iteye.com/blog/1090157"
---

01. namespace ConsoleApplication2
02. {
03. class Program
04. {
05. static void Main(string\[] args)
06. {
07. // 测试代码
08. string a = "100";
09. 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. }