[Aaronyang] C # People love to learn not to learn [4]

Source: Internet
Author: User

This article is not suitable for beginners, only for people who have a certain basis to see. I more believe that the details of knowledge Kako, I started from 4.0 to learn, and finally have time system of learning c#5.0, is 5.0 of the knowledge, will be marked under special. But the content may also contain other versions of the framework of knowledge, but also to facilitate their own better memory of C # knowledge. Article content are their own summary, no plagiarism, if you think the article grade is too low, please Daniel bypass--aaronyang's blog (www.ayjs.net)
1. Generics-generic for C #

1.1 Performance is better than non-generics, such as unpacking the problem. Personal Sense code is more readable. Also, writing code may be a great way to write code. A name that starts with a T and adds meaning to a word, such as converter<tinput,tout>,xx<tkey,tvalue>.

1.2 Title: No Baidu, please enumerate at least 5 for example list<t> common objects in C # using generics

1.3 Write a chain yourself, and use the generics knowledge of the demo

1. Define the chain node, the previous node, the next node, plus the node is OK.

   //Define the chain node, the previous node, the next node , plus the node itself OK     Public classMylinkednode<t> {          PublicMylinkednode (T value) { This. Value =value; }         PublicT value{Get;Private Set;} /// <summary>        ///previous Node Object/// </summary>         PublicMylinkednode<t> Prev {Get; InternalSet; } /// <summary>        ///The latter node object/// </summary>         PublicMylinkednode<t> Next {Get; InternalSet; } }

2. Next, in the encapsulation of a node operation of the Operation class, just review the iterator yield and understand ienumerable<t> this interface, time is limited, here I only first implement AddLast and GetEnumerator

 //Next, because of the chain structure, it is only suitable to add elements from the tail and header, the middle is not convenient to add elements. So the encapsulation class for the operation of the node, the general header adds a node AddFirst (), the tail adds a node addend ()//Remove a node Removefirst (), Removeend (), here I only implement Addend and GetEnumerator first     Public classMylinkedlist<t>: ienumerable<t>    {        /// <summary>        ///The default IEnumerable is defined and must be implemented/// </summary>        /// <returns></returns>         PublicIenumerator<t>GetEnumerator () {//use yield to return the mylinkednode<t> to the IEnumerator .Mylinkednode<t> cur =First ;  while(cur!=NULL)//if the next node is not empty            {                yield returncur.                Value; Cur= cur. Next;//set the current value to the value of the next node}} System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () { returnGetEnumerator (); }        /// <summary>        ///Add a node that is incremented from the tail by default/// </summary>        /// <param name= "Mylinkednode" >value of type in Mylinkednode</param>        /// <returns></returns>         PublicMylinkednode<t>AddEnd (T mylinkednode) {Mylinkednode<T> cur =NewMylinkednode<t>(Mylinkednode); if(First = =NULL)            {                  //if the collection does not have a single node, then the first and last nodes are equal to the current nodeFirst = End =cur; }            Else {              //as the new tail node increases, the last node of the previous tail becomes the node's previous node, and he becomes the last node himself .Mylinkednode<t> Prevend =End; //update the last element of the new oneEnd.prev =Prevend; End.next=cur; End=cur; }            returncur; }        //There are special nodes in the chain structure with the first node and the last node        /// <summary>        ///Mylinkedlist The first element in a collection/// </summary>         PublicMylinkednode<t> First {Get;Private Set; } /// <summary>        ///Mylinkedlist The last element in a collection/// </summary>         PublicMylinkednode<t> End {Get;Private Set; } /// <summary>        ///Add a node in place of the beginning/// </summary>        /// <param name= "Mylinkednode" >Mylinkednode Value</param>        /// <returns></returns>         PublicMylinkednode<t>AddFirst (T mylinkednode) {Throw NewNotImplementedException ();//own Implementation        }        /// <summary>        ///Remove a node/// </summary>        /// <param name= "Mylinkednode" >Mylinkednode Object</param>        /// <returns></returns>         PublicMylinkednode<t>removeend (T mylinkednode) {Throw NewNotImplementedException ();//own Implementation        }    }

3. Use a collection of this data structure

 classProgram {Static voidMain (string[] args) {Mylinkedlist<int> m =Newmylinkedlist<int>(); M.addend (1); M.addend (Ten); M.addend ( -); foreach(varIteminchm) {Console.WriteLine (item+",");        } console.readline (); }    }

Effect

The whole process, the feeling is quite meaningful, especially when the concept of generics into it, your code may be more exciting.

1.4 Types of data structures, just deepened impressions: Queue<t>,dictionary<tkey, Tvalue>, ILookup (TKey, telement), etc.

1.5 Generic default value initialization, for example public T Gett () {t t=default (t); ...     }

1.6 generic constraints and inheritance:

Public abstract class Class1<t>:tenumerable<t>

public class dbmanager<tdb> where Tdb:icommondb,new ()

Aaronyang Expansion: where T:struct/class/interface/ new () constructor constraint, specifies that type T must have a default constructor /other generics, such as where T1:t2

*1.7 static members : Aaronyang: As long as you remember T is not the same, the value of the static member inside is not shared, and will not be affected. Professional terminology: Static members of a generic class can only be shared in one instance of a class

I wrote an example, a look to understand

 classProgram {Static voidMain (string[] args) {OwnStaticGeneric1<string>.obj =4; OwnStaticGeneric1<int>.obj =5; OwnStaticGeneric1<string>.obj =6; OwnStaticGeneric1<int>.obj =7; Console.WriteLine (OwnStaticGeneric1<string>.obj);//=>6Console.WriteLine (ownstaticgeneric1<int>.obj);//=>7OwnStaticGeneric2<string>.obj ="4"; OwnStaticGeneric2<int>.obj =5; OwnStaticGeneric2<string>.obj ="6"; OwnStaticGeneric2<int>.obj =7; Console.WriteLine (OwnStaticGeneric1<string>.obj);//=>6Console.WriteLine (ownstaticgeneric1<int>.obj);//=>7Console.ReadLine (); }    }     Public classOwnstaticgeneric1<t> {         Public Static intobj; }     Public classOwnstaticgeneric2<t>    {         Public StaticT obj; }

1.8 Advanced Knowledge: generic interface, feel like you are the architect of the exam

1.8.1 Expand the keyword usage that might be used in an in modifier that is similar to ref and out, and that the procedure in the body of the method does not overwrite the value of the in Parameter . If you do not understand, you can Baidu, you can also see my example below, but in advance, you'd better understand the basic usage of out,ref.

Some people design interfaces directly iinterface<t1,t2>, and there are also wonderful other formulations that use in or out or ref to modify a generic scene

Explanation: A subclass class implements the Itestin interface, out defines the output type, in defines the input type, must be the value input, so inexplicable itestin<string,object> suddenly understand. Still do not understand, suggest you Baidu

Leave a topic: How to let the user write code can write the following effect, student value is not allowed to change, please design interface

public class student:icustomcomparable<student>{

public int CompareTo (Student stu) {

return ...;

}

}

Refer to part of the answer (the answer font is set to White by me, to see, I choose the following blank part): Public interface icustomcomparable<in t>{int CompareTo (T stu); }

1.8.2 in fact the above in or out modified generics, involving the covariance in the generic knowledge (the generic parameters are out-modified) and the resistance (generic parameters are in the modified) knowledge, do not care too much, will be good!!!!!! Oh! Shit, anti-British (country)

1.9 Nullable<t> T must be a value type, the definition can be empty, interested can look at the implementation of the public struct nullable<t> where t:struct

Equivalent notation: nullable<int> a equals int? A

?? Use: for example, int y=x??   0; If x is null, it is equal to 0, otherwise it is the original value.

1.10 Of course generics can also be used as a method on a class, and this knowledge is too simple to tell

1.11 Generic delegates, lambda expressions are the most typical, such as the Func action, etc., which are spoken in LINQ

1.12 As a developer of more than a year, all know I skipped, where there may be doubt to keep.

====== Anhui Liuan =========www.ayjs.net==========aaronyang======== Yang Yang ==================

[Aaronyang] C # People love to learn not to learn [4]

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.