05.c# generic type (three chapters 3.1-3.2)

Source: Internet
Author: User

Next, the generics in C #, skilled use of generics can improve the reusability of code, using our code instantly on the tall, of course, only a little bit, really only a little bit, because the back to learn and master the knowledge there are many. Let's take a look at the next example of using Dictionary<tkey,tvalue>.

1 Static voidMain (string[] args)2 {3dictionary<int,string> result =GetAll ();4 }5 6  Public Staticdictionary<int,string>GetAll ()7 {8     varDIC =Newdictionary<int,string>();9Dic. ADD (1,"AAA");TenDic. ADD (1,"AAA"); OneDic. ADD (1,"AAA"); A    returndic; -}

The two forms of generics: Generic types (classes, interfaces, delegates, and structs) and generic methods, such as TKey and TValue are type parameters, and the incoming int and string are real types, and you can see that the type parameter is just a placeholder for the real type. Generics that do not provide a true argument for a type parameter are called non-constructed generic types, and an instance of the type is the object that we use if the type argument is specified to be called a constructed type. Diagram.

The judgment of the generic is a headache, and then we have to say, may not be very clear, try, because the book said I do not understand, first in this explanation. If you are not sure, you can read the explanations in the book. Look first.

When we look at such a generic method, we need to replace the parameter type in the actual use (as previously said, the parameter type is actually a placeholder for the type argument), use a string to replace T, use int to replace the TOutput

1  Public Static list<int> GetAll (converter<stringint> conv)2{ 3 }

Where converter<string,int> is a constructed type, conv is a formal parameter and should now know what this generic method does: Using an instance of a converter<string,int> generic delegate as a parameter, Returns a list that contains an integral type.

Please treatise.

05.c# generic type (three chapters 3.1-3.2)

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.