在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
当我们在初学使用C#时,常常会不知道该用StringBuilder合适还是用String高效,下面是我在学习当中对StringBuilder和String的区别总结,分享给大家。 String类有不可改变性。每次执行字符操作时,都会创建一个新的String对象。 StringBuilder 类解决了对字符串进行重复修改的过程中创建大量对象的问题。初始化一个StringBuilder 之后,它会自动申请一个默认的StringBuilder 容量(默认值是16),这个容量是由Capacity来控制的.并且允许,我们根据需要来控制Capacity的大小,也可以通过Length来获取或设置StringBuilder 的长度. 举例: 用String类这么写 1 String begin_query = "select UPPER(MachineName) As MachineName, "+"LOWER(MachineOwner) As MachineOwner, Status, "+ "StartTime from NET_STRESS WHERE "; 2 3 String end_query = " AND StartTime > '" + startTime + "'AND StartTime < '" + endTime + "'"; 4 5 String query = begin_query + GetWhereClause("PASSED") + end_query; 用StringBuilder类这么写: 1 StringBuilder begin_query = new StringBuilder(); 2 3 begin_query.Append("select UPPER(MachineName) As MachineName "); 4 5 begin_query.Append("LOWER(MachineOwner) As MachineOwner, Status, "); 6 7 begin_query.Append("StartTime from NET_STRESS WHERE "); 8 9 StringBuilder end_query = new StringBuilder(); 10 11 end_query.Append(" AND StartTime > '"); 12 13 end_query.Append(startTime); 14 15 end_query.Append("' AND StartTime < '"); 16 17 end_query.Append(endTime); 18 19 end_query.Append("'"); 20 21 String query = begin_query.Append(GetWhereClause("PASSED")).Append(end_query).ToString(); 通过用一个重载的构造函数方法初始化变量,可以创建 StringBuilder 类的新实例,正如以下示例中所阐释的那样。 1 StringBuilder MyStringBuilder = new StringBuilder("Hello World!"); 设置容量和长度 1 StringBuilder MyStringBuilder = new StringBuilder("Hello World!", 25); 另外,可以使用读/写 Capacity 属性来设置对象的最大长度。以下代码示例使用 Capacity 属性来定义对象的最大长度。 1 MyStringBuilder.Capacity = 25; EnsureCapacity 方法可用来检查当前 StringBuilder 的容量。如果容量大于传递的值,则不进行任何更改;但是,如果容量小于传递的值,则会更改当前的容量以使其与传递的值匹配。 1 StringBuilder MyStringBuilder = new StringBuilder("Hello World!"); 2 MyStringBuilder.Append(" What a beautiful day."); 3 Console.WriteLine(MyStringBuilder); 1 int MyInt = 25; 2 StringBuilder MyStringBuilder = new StringBuilder("Your total is "); 3 MyStringBuilder.AppendFormat("{0:C} ", MyInt); 4 Console.WriteLine(MyStringBuilder);
1 StringBuilder MyStringBuilder = new StringBuilder("Hello World!"); 2 MyStringBuilder.Insert(6,"Beautiful "); 3 Console.WriteLine(MyStringBuilder); 此示例将 Hello Beautiful World! 显示到控制台。 1 StringBuilder MyStringBuilder = new StringBuilder("Hello World!"); 2 MyStringBuilder.Remove(5,7); 3 Console.WriteLine(MyStringBuilder);
1 StringBuilder MyStringBuilder = new StringBuilder("Hello World!"); 2 MyStringBuilder.Replace('!', '?'); 3 Console.WriteLine(MyStringBuilder); 此示例将 Hello World? 显示到控制台。
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论