当前位置:Gxlcms > mssql > 编写高质量代码改善C#程序——使用泛型集合代替非泛型集合(建议20)

编写高质量代码改善C#程序——使用泛型集合代替非泛型集合(建议20)

时间:2021-07-01 10:21:17 帮助过:56人阅读

软件开发过程中,不可避免会用到集合,C#中的集合表现为数组和若干集合类。不管是数组还是集合类,它们都有各自的优缺点。如何使用好集合是我们在开发过程中必须掌握的技巧。不要小看这些技巧,一旦在开发中使用了错误的集合或针对集合的方法,应用程序将会背离你的预想而运行。

建议20:使用泛型集合代替非泛型集合

在建议1中我们知道,如果要让代码高效运行,应该尽量避免装箱和拆箱,以及尽量减少转型。很遗憾,在微软提供给我们的第一代集合类型中没有做到这一点,下面我们看ArrayList这个类的使用情况:

  1. ArrayList al=new ArrayList();
  2. al.Add(0);
  3. al.Add(1);
  4. al.Add("mike");
  5. foreach (var item in al)
  6. {
  7. Console.WriteLine(item);
  8. }

上面这段代码充分演示了我们可以将程序写得多么糟糕。

首先,ArrayList的Add方法接受一个object参数,所以al.Add(1)首先会完成一次装箱;其次,在foreach循环中,待遍历到它时,又将完成一次拆箱。

在这段代码中,整形和字符串作为值类型和引用类型,都会先被隐式地强制转型为object,然后在foreach循环中又被转型回来。

同时,这段代码也是非类型安全的:我们然ArrayList同时存储了整型和字符串,但是缺少编译时的类型检查。虽然有时候需要有意这样去实现,但是更多的时候,应该尽量避免。缺少类型检查,在运行时会带来隐含的Bug。集合类ArrayList如果进行如下所示的运算,就会抛出一个IvalidCastException:          

  1. ArrayList al=new ArrayList();
  2. al.Add(0);
  3. al.Add(1);
  4. al.Add("mike");
  5. int t = 0;
  6. foreach (int item in al)
  7. {
  8. t += item;
  9. }

ArrayList同时还提供了一个带ICollection参数的构造方法,可以直接接收数组,如下所示:

  1. var intArr = new int[] {0, 1, 2, 3};
  2. ArrayList al=new ArrayList(intArr);

该方法内部实现一样糟糕,如下所示(构造方法内部最终调用了下面的InsertRange方法):

  1. public virtual void InsertRange(int index, ICollection c)
  2. {
  3. if (c == null)
  4. {
  5. throw new ArgumentNullException("c", Environment.GetResourceString("ArgumentNull_Collection"));
  6. }
  7. if ((index < 0) || (index > this._size))
  8. {
  9. throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
  10. }
  11. int count = c.Count;
  12. if (count > 0)
  13. {
  14. this.EnsureCapacity(this._size + count);
  15. if (index < this._size)
  16. {
  17. Array.Copy(this._items, index, this._items, index + count, this._size - index);
  18. }
  19. object[] array = new object[count];
  20. c.CopyTo(array, 0);
  21. array.CopyTo(this._items, index);
  22. this._size += count;
  23. this._version++;
  24. }
  25. }

概括来讲,如果对大型集合进行循环访问、转型或装箱和拆箱操作,使用ArrayList这样的传统集合对效率影响会非常大。鉴于此,微软提供了对泛型的支持。泛型使用一对<>括号将实际类型括起来,然后编译器和运行时会完成剩余的工作。微软也不建议大家使用ArrayList这样的类型了,转而建议使用它们的泛型实现,如List<T>。

注意,非泛型集合在System.Collections命名空间下,对应的泛型集合则在System.Collections.Generic命名空间下。

建议一开始的那段代码的泛型实现为:           

  1. List<int> intList = new List<int>();
  2. intList.Add(1);
  3. intList.Add(2);
  4. //intList.Add("mike");
  5. foreach (var item in intList)
  6. {
  7. Console.WriteLine(item);
  8. }

代码中被注释的那一行不会被编译通过,因为“mike"不是整型,这里就体现了类型安全的特点。

下面比较了非泛型集合和泛型集合在运行中的效率:

  1. static void Main(string[] args)
  2. {
  3. Console.WriteLine("开始测试ArrayList:");
  4. TestBegin();
  5. TestArrayList();
  6. TestEnd();
  7. Console.WriteLine("开始测试List<T>:");
  8. TestBegin();
  9. TestGenericList();
  10. TestEnd();
  11. }
  12. static int collectionCount = 0;
  13. static Stopwatch watch = null;
  14. static int testCount = 10000000;
  15. static void TestBegin()
  16. {
  17. GC.Collect(); //强制对所有代码进行即时垃圾回收
  18. GC.WaitForPendingFinalizers(); //挂起线程,执行终结器队列中的终结器(即析构方法)
  19. GC.Collect(); //再次对所有代码进行垃圾回收,主要包括从终结器队列中出来的对象
  20. collectionCount = GC.CollectionCount(0); //返回在0代码中执行的垃圾回收次数
  21. watch = new Stopwatch();
  22. watch.Start();
  23. }
  24. static void TestEnd()
  25. {
  26. watch.Stop();
  27. Console.WriteLine("耗时:" + watch.ElapsedMilliseconds.ToString());
  28. Console.WriteLine("垃圾回收次数:" + (GC.CollectionCount(0) - collectionCount));
  29. }
  30. static void TestArrayList()
  31. {
  32. ArrayList al = new ArrayList();
  33. int temp = 0;
  34. for (int i = 0; i < testCount; i++)
  35. {
  36. al.Add(i);
  37. temp = (int)al[i];
  38. }
  39. al = null;
  40. }
  41. static void TestGenericList()
  42. {
  43. List<int> listT = new List<int>();
  44. int temp = 0;
  45. for (int i = 0; i < testCount; i++)
  46. {
  47. listT.Add(i);
  48. temp = listT[i];
  49. }
  50. listT = null;
  51. }

输出为:

开始测试ArrayList:

耗时:2375

垃圾回收次数:26

开始测试List<T>:

耗时:220

垃圾回收次数:5

以上介绍了编写高质量代码改善C#程序——使用泛型集合代替非泛型集合(建议20),有关编写高质量代码建议1到建议157,本完整会持续更新,敬请关注,谢谢。

您可能感兴趣的文章:

  • C#中把任意类型的泛型集合转换成SQLXML数据格式的实例
  • C#控制台基础 List泛型集合与对应的数组相互转换实现代码
  • C#中Dictionary泛型集合7种常见的用法
  • C#泛型集合Dictionary<K,V>的使用方法
  • C#读取数据库返回泛型集合详解(DataSetToList)
  • C#实现将类的内容写成JSON格式字符串的方法
  • c#使用htmlagilitypack解析html格式字符串
  • C#中利用LINQ to XML与反射把任意类型的泛型集合转换成XML格式字符串的方法

人气教程排行