分类目录

链接

2012 年 5 月
 123456
78910111213
14151617181920
21222324252627
28293031  

近期文章

热门标签

新人福利,免费薅羊毛

现在位置:    首页 > .NET > 正文
C#编程建议1:正确操作字符串
.NET 暂无评论 阅读(2,226)
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Tip1
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. }
  13.  
  14. private static void NewMethod1()
  15. {
  16. string s1 = "abc";
  17. s1 = "123" + s1 + "456";    //以上两行代码创建了3个
  18. //字符串对象,并执行了一次string.Contact方法
  19. }
  20.  
  21. private static void NewMethod6()
  22. {
  23. string re6 = 9 + "456";     //该代码发生一次装箱,并调
  24. //用一次string.Contact方法
  25. }
  26.  
  27. private static void NewMethod2()
  28. {
  29. string re2 = "123" + "abc" + "456"; //该代码等效于
  30. //string re2 = "123abc456";
  31. }
  32.  
  33. private static void NewMethod9()
  34. {
  35. const string a = "t";
  36. string re1 = "abc" + a;     //因为a是一个常量,所以
  37. //该代码等效于 string re1 = "abc" + "t";
  38. //最终等效于string re1 = "abct";
  39. }
  40.  
  41. private static void NewMethod8()
  42. {
  43. string a = "t";
  44. += "e";
  45. += "s";
  46. += "t";
  47. }
  48.  
  49. private static void NewMethod7()
  50. {
  51. string a = "t";
  52. string b = "e";
  53. string c = "s";
  54. string d = "t";
  55. string result = a + b + c + d;
  56. }
  57.  
  58. private static void NewMethod10()
  59. {
  60. //为了演示必要,定义了4个变量
  61. string a = "t";
  62. string b = "e";
  63. string c = "s";
  64. string d = "t";
  65. StringBuilder sb = new StringBuilder(a);
  66. sb.Append(b);
  67. sb.Append(c);
  68. sb.Append(d);
  69. //再次提示,是运行时,所以没有使用下面的代码
  70. //StringBuilder sb = new StringBuilder("t");
  71. //sb.Append("e");
  72. //sb.Append("s");
  73. //sb.Append("t");
  74. string result = sb.ToString();
  75. }
  76.  
  77. private static void NewMethod11()
  78. {
  79. //为了演示必要,定义了4个变量
  80. string a = "t";
  81. string b = "e";
  82. string c = "s";
  83. string d = "t";
  84. string.Format("{0}{1}{2}{3}", a, b, c, d);
  85. }
  86.  
  87. }
  88. }

============ 欢迎各位老板打赏~ ===========

本文版权归Bruce's Blog所有,转载引用请完整注明以下信息:
本文作者:Bruce
本文地址:C#编程建议1:正确操作字符串 | Bruce's Blog

发表评论

留言无头像?