. A preliminary study of net generics

Source: Internet
Author: User

It is always known that. NET appears in the. NET Framework 2.0, why the introduction of generics in 2.0, because Microsoft in the beginning to develop the. NET Framework does not think of multiple types of parameters in the transfer of the method of refactoring, so that developers have to face the transmission of many types of parameters and not to write multiple methods, but the developer's wisdom is infinite, creativity has been excavated, before the generics, there is Developers are thinking of using the object type to pass parameters to the parameter type in order to mention the code utilization, which undoubtedly solves the problem of multiple types of parameter transfer and the need to write multiple methods. So why does the object type implement many different types of parameters? Why design generics if you have an object type? What's so bad about the type of object? In fact, a bit of a basic developer should know that the object type is the parent class of all types, through the Richter conversion principle we know that all of the parent class can be replaced with a subclass, so that you can receive multiple parameters, and because the object type of the conversion of the impact of the unboxing on the performance, At 2.0, Microsoft introduced generics.

Below, we introduce the declaration and invocation of generics:

1     Public Static void Show<t>(T tparameter)2      {3            Console.WriteLine ($" This is{typeof (genericclass)}show<t>,paratype={tparameter.gettype ()},value={tparameter} " ); 4       }

Printed content We do not need to pay attention to, we only look at the method head, we can see the method header and parameter added T this letter, in fact, this is the rule of the generic Declaration, generics in the declaration, the method header need to add <T> (T parm),
Note that the letters inside the angle brackets are variable and can be any letter, but the letters inside the angle brackets must be the same as the letters in the argument, so a method is declared.

Next we look at the generic invocation procedure, how generics declare parameter types in the case of unnamed parameter types, at the bottom of the program entry I wrote two list types

1   class Program2     {3         Static voidMain (string[] args)4         {5             Try6             {7                 8Console.WriteLine (typeof(list<int>));9Console.WriteLine (typeof(list<string>));

Run we found that tlist although not know what type to pass when calling, but add placeholder, then what is the placeholder? We see ' 1 in DOS, yes, this is the placeholder. So when was the locator declared? On the Code

    classProgram {Static voidMain (string[] args) {            Try            {                intIparameter =123; LongLparameter =456; stringSparameter ="ABC"; ObjectOparameter ="123456"; Console.WriteLine ("**********************");                Commonclass.showint (Iparameter);                Commonclass.showlong (Lparameter);                Commonclass.showstring (Sparameter); Console.WriteLine ("**********************");                Commonclass.showobject (Oparameter);                Commonclass.showobject (Iparameter);                Commonclass.showobject (Lparameter);                Commonclass.showobject (Sparameter); Console.WriteLine ("**********************"); Genericclass.show<Object>(Oparameter); Genericclass.show<int>(Iparameter); //genericclass.show<int> (lparameter);//the specified type must be the same as the parameterGenericclass.show (Iparameter);//not specified, automatically inferred by the compilergenericclass.show<Long>(Lparameter); Genericclass.show<string>(Sparameter); Console.WriteLine ("**********************"); }            Catch(Exception ex) {Console.WriteLine (ex).            Message);        } console.read (); }    }}

Here I will not repeat, directly to say, in fact, the generic in the Declaration of what type (with a placeholder), is in the call when the compiler automatically calculate, also can be specified at the time of invocation, this is a deferred thought delay declaration: The argument type declaration, deferred to the call, deferred all can be postponed, This is also a thought of design patterns. After the compilation of generics and the normal method is the same, so does not affect performance, you can imagine another overload

Benefits of Generics: One method supports a variety of parameter types, and performance is non-lossy.

Generics support multiple parameters imaginable, but is there really no loss? Not clear, good, for everything we have to look at a skeptical attitude, science will be confirmed, then here we test. Classes used: Stopwatch

1                 LongCommontime =0;2                 LongObjecttime =0;3                 LongGenerictime =0;4                 {5Stopwatch Watch =NewStopwatch ();6 Watch. Start ();7                      for(inti =0; I <100000000; i++)8                     {9 Commonclass.showobject (iparameter);Ten                     } One Watch. Stop (); AObjecttime =Watch. Elapsedmilliseconds; -                 } -                 { theStopwatch Watch =NewStopwatch (); - Watch. Start (); -                      for(inti =0; I <100000000; i++) -                     { + Commonclass.showint (iparameter); -                     } + Watch. Stop (); ACommontime =Watch. Elapsedmilliseconds; at                 } -                 { -Stopwatch Watch =NewStopwatch (); - Watch. Start (); -                      for(inti =0; I <100000000; i++) -                     { ingenericclass.show<int>(iparameter); -                     } to Watch. Stop (); +Generictime =Watch. Elapsedmilliseconds; -                 } theConsole.WriteLine ("commontime={0}", commontime); *Console.WriteLine ("objecttime={0}", objecttime); $Console.WriteLine ("generictime={0}", generictime);

The three classes inside are the object type and the normal class, and the generic, respectively, for int, string, and entity type calls, and I answer directly:

By the run time given on the graph, the generics are the quickest, then the common method, then the object type, you know, I this is the result of running 100 million times, in fact, we also come to the conclusion that the object type does have performance impact, the single is not the most heinous, It is also not to be used, but also to see the environment in which the program is located.

To add, generics are not syntactic sugars, and syntactic sugars are a feature of the compiler's offering, and don't misunderstand.

. A preliminary study of net generics

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.