c # generics learning (a)

From the beginning .net 2.0 support for generics. Generics can help us create independent of the type contained classes and methods.

You do not have to write different types of the same functionality as methods or classes, as long as creating a generic class or method can realize the operation of multiple types of data.

Although the type of object can also make you realize such a function, but it is not type-safe.

Generics is not only a structure of c # language and the CLR is defined. Therefore, the generic class defined in c #, may be a particular instantiation of the generic type with the vb.

Implementation and realization of generic object 

 

   static void Main(string[] args)
        {
            // the System.Collections namespace following ArrayList class, the object is stored
             // the Add () method, the value of the addition type data, parameters need to be boxed, into object type, when accessing data, you need to
             // data We were unpacking, to be cast. 
            var List = new new the ArrayList ();
            list.Add(44);
            int i1 = (int)list[0];
            foreach (int item in list)
            {
                Console.WriteLine(item);
            }
            // the System.Collections.Generic namespace following List <T>, is a generic class.
            // type is defined as int, int type is used in so dynamically generated class jit compiler generates a new type after compilation. This type is to accept a parameter of type int
             // no longer unpacking and packing.
            //
             var IList = new new List < int > ();
            ilist.Add(44);
            int i2 = ilist[0];
            foreach (var item in ilist)
            {
                Console.WriteLine(item);
            }

         
            Console.ReadKey();
        }

 

 If you add the following two lines of code:

     list.Add("hello");
               ilist.Add("hello");

When using the generic, not compile;

And when using the object, the compiler can, but when accessing data, boxing and unboxing will be reported anomalies.

Therefore, with respect to the generic Object, type-safe, better performance.

 

Guess you like

Origin www.cnblogs.com/andonglu/p/11076500.html