Introduction to the generics of Visual C # generic Learning

Source: Internet
Author: User
Tags copy count implement interface reference
Visual What is generic





a type placeholder, or a type parameter. We know that in a method, the value of a variable can be used as a parameter, but the type of the variable itself can also be used as a parameter. Generics allow us to specify what this type parameter is when called. The two obvious benefits that generics can bring to us in. NET are type safety and reduced boxing, unboxing.





type safety and boxing, unboxing





as a type parameter, generics are easy to provide type safety. And before, in. net1.1 we want to implement type-safe to do this:





//Suppose you have a collection of people





public class person{


private string _name;


public string Name


{get {return _name;}


set {_name = value;}}


}





//Suppose you have a collection of people





public class Personcollection:ilist


{


 ...


private ArrayList _persons = new ArrayList ();


public Person This[int index]


{get {return (person) _persons[index];}}





public int Add (person item)


{_persons.add (item);


return _persons.count-1;}





public void Remove (person item)


{_persons.remove (item);}





Object Ilist.this[int Index]


{get {return _persons[index];}


set {_persons[index] = (person) value;}





int Ilist.add (object item)


{return ADD (person) item);





void Ilist.remove (object item)


{Remove (person) item;}


  ...


}


The above code mainly uses the explicit interface members (explicit interface member implementation) technology, can realize type safety, but the problem is:





produces duplicate code. Suppose you have a collection of dog classes that have the same functionality, but for type safety you have to copy a piece of code, which makes the program repeat code more difficult to maintain when faced with changes.





public class Dogcollection:ilist


{


 ...


private ArrayList _dogs = new ArrayList ();


public Dog This[int index]


{get {return (DOG) _dogs[index];}}





public int Add (DOG item)


{_dogs.add (item);


return _dogs.count-1;}





public void Remove (Dog item)


{_dogs.remove (item);}





Object Ilist.this[int Index]


{get {return _dogs[index];}


set {_dogs[index] = (Dog) value;}}





int Ilist.add (object item)


{return Add ((DOG) item);}





void Ilist.remove (object item)


{Remove (DOG) item);}


  ...


}


if you want to implement type safety in generics, you don't need to copy any code, you just have to do this:





list<person> persons = new list<person> ();


persons. ADD (New Person ());


person person = persons[0];


list<dog> dogs = new list<dog> ();


dogs. ADD (New Dog ());


Dog Dog = dogs[0];





• Additional boxing and unboxing are required for value-type objects. In fact, for the traditional collection, as long as the content involved in the value of the type, it is inevitable to need to box, unboxing. Take a look at the example below.





public class Intcollection:ilist


{


 ...


private ArrayList _ints = new ArrayList ();


public int This[int index]


{get {return (int) _ints[index];}}





public int Add (int item)


{_ints.add (item);


return _ints.count-1;}





public void Remove (int item)


{_ints.remove (item);}


Object Ilist.this[int Index]


{get {return _ints[index];}


set {_ints[index] = (int) value;}}





int Ilist.add (object item)


{return Add ((int) item);}





void Ilist.remove (object item)


{Remove ((int) item);}


  ...


 }





static void Main (string[] args)


{intcollection ints = new Intcollection ();


INTs. ADD (5); Packing


int i = ints[0]; Split Box


 }


a small number of boxing, unboxing has little impact on performance, but if the data volume of the collection is very large, it has a certain impact on performance. Generics can avoid boxing and unboxing operations on value types, and you can verify that the compiled IL is parsed.





static void Main ()





{


list<int> ints = new list<int> ();


INTs. ADD (5); No boxing


int i = ints[0]; No unpacking,
.

}

the realization of
generic type





Generic Method





static void swap<t> (Ref t A, ref T B)


{Console.WriteLine ("You sent this Swap () method a {0}",


typeof (T));


T temp;


temp = A;


a = b;


B = temp;


}


generic class, Structure





public class point<t>


{


private T _x;


private T _y;


Public T X


{get {return _x;}


set {_x = value;}}





Public T Y


{get {return _y;}


set {_y = value;}}





public override string ToString ()


{return string. Format ("[{0}, {1}]", _x, _y); }


}

Where
<b>the</b>
generic



The
generic's where can qualify the type parameters. There are several ways to do this.





where t:struct constraint type parameter T must inherit from System.ValueType.


  


where T:class constraint type parameter T must be a reference type, that is, it cannot be inherited from System.ValueType.




The
where t:new () constraint type parameter T must have a default constructor





where T:nameofclass constraint type parameter T must inherit from a class or implement an interface.





These limitations can be combined, such as: public class point&lt;t&gt; where T:class, IComparable, new ()




the mechanism of
generic type





mechanism:





C # Generic code uses special placeholders to represent generic types when compiled into IL code and without data, and supports generic operations with proprietary IL directives. The true generics instantiation works in a "on-demand" manner, which occurs at JIT-compilation time.





compilation mechanism:





1. At the first compile time, the compiler generates only "generic" IL Code and metadata-----for the stack&lt;t&gt; (stack algorithm) type and does not instantiate the generic type, and T only acts as a placeholder in the middle





2. At JIT compilation time, when the JIT compiler encounters stack&lt;int&gt; for the first time, an int replaces the generic version IL code with the t---in the metadata to instantiate the generic type. The CLR produces the same code for a generic type with all type parameters of reference type, but if the type argument is a value type, the CLR generates a separate code for each of the different value types.




some problems of
generic type




Operator overloading is not supported by
. That's all I know,
.



the significance of
model




What is the meaning of
generics? Type safety and the reduction of boxing and unboxing are not generic meanings, but rather the two benefits of generics (perhaps the most obvious benefit in. NET generics). The significance of generics is that-by taking the type as an argument, it implements a good horizontal connection between the code, and we know that inheritance provides a vertical link from the top down to the code, but generics provide a convenient horizontal connection (to some extent, it has something to do with AOP). In the personcollection example, we know that the add () method and the Remove () method have the same parameter types, but we definitely can't tell our program this, generics provide a mechanism for the program to know. Although the rationale is simple, such a mechanism may bring some far-reaching changes to our process.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.