. NET generic 01. Why do I need generic, basic generic syntax, and basic. net syntax?

Source: Internet
Author: User

. NET generic 01. Why do I need generic, basic generic syntax, and basic. net syntax?

. NET generics may be based on C ++ generic templates, which can be used to abstract and process types and decouple types and methods. One of the most classic applications is to implement generic processing for various Domain Models in the base interface and base class in a three-tier architecture targeting different domain models.

 

This article mainly includes:
■ Why generic
※No generic type is required.
※Use generic
※Nature of generic Runtime
■ Generic syntax
■ Typical generic classes

 

Why generic

No generic

Let's look at a comparison method.

public class Calculator    {        public static bool AreEqual(int value1, int value2)        {            return value1 == value2;        }    }


Called on the client.

Class Program {static void Main (string [] args) {bool result = Calculator. areEqual (1, 2); if (result) {Console. writeLine ("Equal");} else {Console. writeLine ("Unequal");} Console. readKey ();}}


Running result: not supported

 

Disadvantage 1: Non-type security

If we want to use the current method to compare the string type.

bool result = Calculator.AreEqual("A", "B");

The compiler reports an error. From this point of view, the AreEqual () method is not a type-safe method. When the string type is input, the compiler reports an error.

 

If you change the parameter type of the AreEqual () method to object, the compiler will not report an error.

public class Calculator    {        public static bool AreEqual(object value1, object value2)        {            return value1 == value2;        }    }

Above, the operation is also normal.

 

Disadvantage 2 of non-Generic Model: boxed and unpacked, resulting in lower performance

Currently, for AreEqual (object value1, object value2), there is no problem in the method itself, but when the client calls it, for example, we still want to compare the value type.

bool result = Calculator.AreEqual(1, 2);

During runtime, when parameters 1 and 2 of the integer value type are passed and assigned to the reference type parameters value1 and value2 in AreEqual (object value1, object value2, A "Packing" operation occurred. When the reference type is converted to the value type, another "binning" Operation occurs, which leads to lower performance.

 

Use generic

Change AreEqual () to a generic method.

public class Calculator    {        public static bool AreEqual<T>(T value1, T value2)        {            return value1.Equals(value2);        }    }

 

Therefore, on the client, you can:

bool result = Calculator.AreEqual<string>("A", "A"); bool result = Calculator.AreEqual<int>(5, 3);

 

As a result, the benefits of using generics are:
1. decoupling methods and types is implemented.
2. It does not cause type conversion and avoids performance problems caused by packing and unpacking.
3. Generics ensure absolute type security.

 

Of course, you can also place the T position on the class:

public class Calculator<T>    {        public static bool AreEqual(T value1, T value2)        {            return value1.Equals(value2);        }    }

 

Then use the following code:

bool result = Calculator<string>.AreEqual("A", "A"); bool result = Calculator<int.AreEqual(1, 2);


 

Nature of generic Runtime

The CLR has dedicated IL commands to support generic operations.
→During initial compilation, the IL code and metadata are generated. T is only a type placeholder and is not instantiated during compilation.
→ Replace the T placeholder in the metadata with the actual type during JIT compilation
→ Convert metadata into local code

 

Generic syntax

class MyArray<T> where T : Student, new(){    private T[] _items;    public T myData;    public MyArray()    {        myData = default(T);    }    public void Add(T item)    {}}

To create a generic instance, you must specify the actual data type:
MyArray <Int32> myArr = new MyArray <Int32> ();

 

The default value of the value type is 0, the default value of the reference type is null, and the default value of the generic type is used:
MyData = default (T );

 

Generic constraints:
T: base class name, indicating that the base class name must be a derived class
T: new (), indicating that the constructor must have no parameters, and the new () constraint must be placed at the end.
T: struct, indicating that it must be a value type
T: class, indicating that it must be of the reference type
T: Interface Name, indicating that the interface must be implemented or the interface that implements the interface

 

A generic class is essentially a class and can still be inherited:

internal class GenericeComparer<T> : Comparer<T> where T : IComparable<T>class MyArray<T> : ArrayList

 

Typical generic classes

In the namespace System. Collections. Generic and System. Collections. ObjectModel, different Generic classes and Generic interfaces are defined. These Generic types are mostly set classes.

List <T> corresponding ArrayList collection class
SortedList <TKey, TValue> corresponds to SortedList collection class
Queue <T> first-in-first-out collection class
Stack <T> back-to-first-out collection class
Collection <T> the base class of the custom generic set
Dictionary <TKey, TValue> corresponds to the Hashtable collection class

 

References:
NET (version 2nd), Author: Wang Tao.

 

". NET generic" series include:

. NET generic type 01. Why do I need generic, basic generic syntax. NET generic type 02, and generic usage?
What is generic? Why does NET Framework Support generics?

The generic type can be any type, int, string, or double. The wildcard type can be used to add anything to it. You can return a specific type or save a value of the same type according to the actual situation.
I have answered similar questions by referring to this address.
Reference: zhidao.baidu.com/question/439325530.html? Oldq = 1
 
What is the difference between generic and generic sets?

In fact, it should not be said that the two are different. They are an inclusive relationship!

There is a term in Object-Oriented Programming called generalization, and the source of this generic is exactly here! The so-called generic type means that the parent type is stored, and the child type is declared during use.

In java or C #, all types are based on the basic object type. It can be considered that all other types are generic objects.

A generic set refers to a set that puts these generic types together. However, you must select the type to add a description before use.

For example, List <T> is a generic set. You can put all the generics in this set. However, the T type must be selected as the prerequisite; otherwise, the T type cannot be entered. This involves the storage problem. For some collections, for example, we can declare such an array int [] a = new int [10]. Once declared, the size cannot be changed. If we do not know the number of data records to be saved, we suppose that we store 10 int records. You can use int [] a = new int [10]; of course there is no objection, but the problem is that as the program runs, we can require no more than 10, but this array cannot be extended; or you may say, int [] a = new int [1000]; certainly enough, but there is a lot of internal space to waste! Therefore, we have considered another type of array, which is very good. However, since the array must be packaged when it is put into the array, unpacking is a great waste of cpu usage.

In. net framework2.0 adds support for generics, that is, implementing the IList interface. It has both the array feature and the length feature that can be increased to a smaller value, but still avoids packaging problems, this is also in. after net 2.0, Microsoft said that there was no reason why arraylist was used to support generics!

In fact, due to long-term habits, generics refer to Collection types such as arrays that implement the IList interface. Therefore, when we call generic or generic sets, they are actually the same concept!

Related Article

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.