Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use generic sets instead of non-generic sets in C # programs

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

It is believed that many inexperienced people do not know what to do about how to use generic sets instead of non-generic sets in C # programs. Therefore, this paper summarizes the causes and solutions of the problems. Through this article, I hope you can solve this problem.

In the process of software development, collections are inevitably used. Collections in C # are represented by arrays and several collection classes. Whether they are arrays or collection classes, they all have their own advantages and disadvantages. How to make good use of collections is a skill that we must master in the development process. Don't underestimate these techniques. Once you use the wrong collection or approach to the collection in your development, the application will run away from your expectations.

Use generics instead of non-generics

If you want your code to run efficiently, you should avoid boxing and unpacking as much as possible, and minimize transformation. Unfortunately, we didn't do this in the first generation of collection types provided by Microsoft, so let's take a look at the use of the class ArrayList:

ArrayList al=new ArrayList (); al.Add (0); al.Add (1); al.Add ("mike"); foreach (var item in al) {Console.WriteLine (item);}

The above code fully demonstrates how badly we can write the program.

First, ArrayList's Add method accepts an object parameter, so al.Add (1) will first complete a boxing; second, in the foreach loop, when it is traversed, it will be unboxed again.

In this code, both the integer and the string, as value and reference types, are implicitly cast to object and then back in the foreach loop.

At the same time, this code is also non-type safe: although ArrayList stores both integers and strings, it lacks compile-time type checking. Although it is sometimes necessary to achieve this intentionally, more often, it should be avoided as much as possible. Lack of type checking brings implicit Bug at run time. The collection class ArrayList throws an IvalidCastException if it does the operations shown below:

ArrayList al=new ArrayList (); al.Add (0); al.Add (1); al.Add ("mike"); int t = 0; foreach (int item in al) {t + = item;}

ArrayList also provides a constructor with an ICollection parameter, which can receive arrays directly, as shown below:

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

The internal implementation of the method is just as bad, as shown below (the following InsertRange method is finally called inside the constructor):

Public virtual void InsertRange (int index, ICollection c) {if (c = = null) {throw new ArgumentNullException ("c", Environment.GetResourceString ("ArgumentNull_Collection"));} if ((index)

< 0) || (index >

This._size) {throw new ArgumentOutOfRangeException ("index", Environment.GetResourceString ("ArgumentOutOfRange_Index"));} int count = c.Count; if (count > 0) {this.EnsureCapacity (this._size + count); if (index < this._size) {Array.Copy (this._items, index, this._items, index + count, this._size-index);} object [] array = new object [count] C.CopyTo (array, 0); array.CopyTo (this._items, index); this._size + = count; this._version++;}}

In a nutshell, if large collections are iterated, transformed, or boxed and unboxed, using traditional collections such as ArrayList can have a significant impact on efficiency. In view of this, Microsoft provides support for generics. Generics use a pair of parentheses to enclose the actual type, and then the compiler and runtime do the rest. Microsoft also doesn't recommend using types like ArrayList, and instead suggests using their generic implementations, such as List.

Note that the non-generic collection is under the System.Collections namespace, and the corresponding generic collection is under the System.Collections.Generic namespace.

It is recommended that the generic implementation of the initial code is as follows:

List intList = new List (); intList.Add (1); intList.Add (2); / / intList.Add ("mike"); foreach (var item in intList) {Console.WriteLine (item);}

The commented line in the code will not be compiled, because "mike" is not an integer, which reflects the characteristics of type safety.

The following compares the efficiency of non-generic and generic collections in operation:

Static void Main (string [] args) {Console.WriteLine ("start testing ArrayList:"); TestBegin (); TestArrayList (); TestEnd (); Console.WriteLine ("start testing List:"); TestBegin (); TestGenericList (); TestEnd ();} static int collectionCount = 0; static Stopwatch watch = null; static int testCount = 10000000 Static void TestBegin () {GC.Collect (); / / forces instant garbage collection of all code GC.WaitForPendingFinalizers (); / / suspends the thread and executes the finalizer (that is, destructor) GC.Collect () in the Terminator queue; / / garbage collects all code again, mainly including the object collectionCount = GC.CollectionCount (0) from the finalizer queue / / returns the number of garbage collections performed in code 0: watch = new Stopwatch (); watch.Start ();} static void TestEnd () {watch.Stop (); Console.WriteLine ("time:" + watch.ElapsedMilliseconds.ToString ()); Console.WriteLine ("garbage collection times:" + (GC.CollectionCount (0)-collectionCount)) } static void TestArrayList () {ArrayList al = new ArrayList (); int temp = 0; for (int I = 0; I < testCount; I +) {al.Add (I); temp = (int) al [I];} al = null;} static void TestGenericList () {List listT = new List (); int temp = 0; for (int I = 0) I < testCount; iTunes +) {listT.Add (I); temp = listT [I];} listT = null;}

The output is:

Start testing ArrayList:

Time consuming: 2375

Garbage collection times: 26

Start testing List:

Time: 220

Garbage collection times: 5

After reading the above, have you mastered how to use generic sets instead of non-generic sets in C # programs? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report