C #2 core infrastructure (I)-generic

Source: Internet
Author: User

In the following sections, I will introduce the most important features added in C #2.

1) generics --- as the most important new feature of C #2 (also the most important new feature in. NET2.0 CLR), generics implement parameterization of types and methods.

2) can be empty-the value type does not have the concept of "value does not exist. With an empty type, it can indicate that "a meaningful value is missing ".

3) delegate --- although the delegate has not changed at the CLR level, C #2 makes it easier to use them. In addition to the simplified syntax and the introduction of anonymous methods, it also guides us to adopt a more functional programming style-this trend has been extended in C #3.

4) iterator-although the C # foreach statement can be used for a long time, in C #1, it is a painful thing to achieve. C #2 the compiler can help you build a state machine behind the scenes, thus hiding a lot of complexity.

For most people, Generics will become the most important new feature of C #2. They enhance performance, make the code more expressive, and move a large number of security checks from execution to compilation. Basically, generics implement the "parameterization" of types and methods, just like in common method calls, parameters are often used to tell them what values to use. Similarly, generic types and methods allow parameters to tell them what type to use.

Understanding all aspects of generics is not an easy task. In this way, I still use simple examples to learn about generics. A collection class provided by. NET2.0: Dictionary <TKey, TValue>.

Using System; using System. collections. generic; using System. text. regularExpressions; class generic Dictionary {static Dictionary <string, int> CountWords (string text) {// create a new ing between words and frequency, it effectively counts the frequency of occurrence of each word in a given Text Segment Dictionary <string, int> frequencies; frequencies = new Dictionary <string, int> (); /* divide the text into words. For each word, check whether it already exists in the ing. If so, increase the existing count; otherwise, an initial count of 1 */string [] words = Regex is assigned to the word. split (text, @ "\ W +"); foreach (string word I N words) {if (frequencies. containsKey (word) {/* Note the following: the code responsible for increasing the number does not need to execute the forced type conversion to the int, You can execute the addition operation: the retrieved value is of the int type at compilation. To increase the count, perform a value operation on the ing indexer first, then add it, And then assign values to the indexer. */Frequencies [word] ++;} else {frequencies [word] = 1 ;}} return frequencies;} public static void Main () {Console. write ("Please input the text:"); string text = Console. readLine (); Dictionary <string, int> frequencies = CountWords (text); // print each key/value pair in the ing. Foreach (KeyValuePair <string, int> entry in frequencies) {string word = entry. key; int frequency = entry. value; Console. writeLine ("{0 }:{ 1}", word, frequency);} Console. read ();}}

The running effect is as follows:

Now that we have read an example, let's take a look at the true meaning of Dictionary <TKey, TValue>, what are TKey and TValue, and why should we close them with Angle brackets. There are two forms of generics: generic types (including classes, interfaces, delegates, and structures) and generic methods. Both are basic APIs (whether a generic method or a complete generic type ).

A type parameter is a placeholder for a real type. In the generic declaration, type parameters should be placed in a pair of angle brackets and separated by commas. Therefore, in Dictionary <TKey, TValue>, the type parameters are TKey and TValue. When using a generic type or method, you need to use a real type instead. These real types are called type argument. In the above Code, the type real parameter is string (instead of TKey) and int (instead of TValue ).

If the type parameter is not provided for any type parameter, the declared type is unbound generic type ). If a type parameter is specified, the object becomes a constructed type ). We know that types (whether generic or not) can be seen as the blueprint of objects. Similarly, unbound generic types are constructed type blueprints, which are an additional abstraction layer. Link example:

More complex, the constructed types can be open or closed. Open type also contains type parameters, while closed type is not open, and each part of the type is clear. In C # code, the only place that can see unbound generics (except as declarations) is in the typeof operator. Type parameter "receive" information, type parameter "provide" information. This idea is the same as the method parameters/method arguments. Only the real parameter of the type must be of the type, but cannot be any value. You can only know the type of the type parameter during compilation. It can be a type parameter in (or include) the context.

For more information, see <TKey, TValue>.

 

When describing a generic type to others, the pronunciation of a wildcard generally uses of to introduce the type parameter or real parameter. Therefore, List <T> is read as list of T. When there are multiple type parameters, you can use a word that fits the meaning of the entire type to separate them. For example, I often use dictionary of string to int to emphasize the ing part, instead of using tuple of string and int.

Although the naming rules for type parameters can use types with T, U, and V, they do not know what they actually mean or how they should be used. In contrast, the names such as Dictionary <TKey, TValue> are much better. TKey indicates the keys type, while TValue indicates the values type. If there is only one parameter type and its meaning is clear, T (List <T> is a good example ). If there are multiple type parameters, you should name them according to their meanings and use the T prefix to specify that this is a type parameter.

 

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.