Personal notes 2.0 New Features

Source: Internet
Author: User
C #2.0 syntax changes: ① generics: Why should I introduce generics? For example, to define a System. collection. in ArrayList, the elements in it are of the object type. When extracting the data from it, you need to forcibly convert the type to ClassA tmp = myArrayList [0] as ClassA. There are two problems, one is the performance overhead of forced type conversion, and the other is type security (errors may occur during compilation but running ). In. net1.0, there are many similar cases, and the introduction of generics aims to better solve this problem. The so-called generic type means that multiple data types can be operated on the same code using parameterized types. Generic programming is a programming paradigm that abstracts types by using parametric types to achieve more flexible reuse. Let's take a look at the code: class Stack <T> {private T [] store; private int size; public Stack () // constructor {store = new T [10]; size = 0;} public void Push (T tmp) {store [size ++] = tmp;} public T Pop {return store [-- size] ;}} the above is a generic implementation. when instantiating this class, we can name the Stack <int> aaa = new Stack <int> (); the int type can only be put into this stack, for example, aaa. push (17); yes; but aaa. push ("123"); Compilation fails. Class C <U, V >{} class D: C <string, int >{} class E <U, V >:c <U, V >{} class F <U, V >:c <string, int >{} these are all generic implementations, which will not be explained here ~ Generics can also be applied to interfaces and delegation, but there are still some practical problems in actual programming. It is worth mentioning the following example: (where) class MyClass <S, T> where S: A/S inherited from A where T: B // T inherited from B {......} ② The anonymous method and iterator; the anonymous method is actually nothing. Compare the two sections of the Code in the example to understand: (C #1.0): + = new EventHandler (button#click ); private void button#click (object sender, EventArgs e) {TextBox1.Text = "123";} after the anonymous method is available (C #2.0 ): button1.Click + = delegate {TextBox1.Text = "123";} For the anonymous method, to be honest, I think it is just to save a few lines of code that is easier to Process delegation, it's just a "trick" of C # compiler ...... then there is the "iterator": there is no such thing If you need to create a set (which can be used for foreach loops), you need to implement Public class MyCollection: Ienumerable {public MYEnumerator GetEnumerator () {return new MyEnumerator (this);} public class MyEnumerator: ienumerator {public void Reset (){...} Public bool MoveNext (){...} Public int Current {...} Object IEnumerator. Current {get {... }}}} With an iterator, you can: public class Stack <T>: IEnumerable <T> {T [] items; int count; public void Push (T data ){...} Public T Pop (){...} Public Ienumerator <T> GetEnumerator () {for (int I = count-1; I> = 0; -- I) {yield return items [I] ;}} is relatively simple, you can see that there are two places that are somewhat fresh: 1) the yield keyword is added; 2) the iterator is used to create reverse traversal: public Ienumerable <T> Bottom ToTop {get {for (int I = 0; I <count; I ++>) {yield return items [I] ;}} ③ division type definition: The Division type allows us to divide a class, structure, or interface into several parts, which are not used separately. cs file. Of course, the namespaces of each part must be the same, and the access protection modifiers cannot conflict with each other. To implement this, we introduced half of the keyword partial, which is called half because it only has the meaning of the keyword when it is put together with class, struct, and interface. The practical significance of the division type is that some of our code files are generated by some tools (such as using some Ing tools or self-written code generation work, to generate some basic entity classes, Data Handler classes, etc.). These code files can be separated by n parts without being put together with the manually added code. Finally, the simple code is used as an example: partial class MyClass {public void test1 (){....}} partial class MyClass {public void test2 (){....}} the code can be written in this way, and the compiler will compile each part together, with no substantive difference. ④ Nullable Generic Structure: The Nullable generic structure allows a value type to have a "null" meaning, so as to facilitate operations in many cases, such as null fields in the database. Int? A = null; if (a = null) {// if a is null, then ....;} else {// if a is not blank, then ....;} the null type is actually a generic type System. nullable <T>. ⑤ Static class: the problem is really simple. A static class is a class that only contains static members. Example: static class MyStaticClass {public const int aaa; public static void Test1 (){//......} Data Access ① model adjustment: for example, in ado. in net1.0, SqlConnection and OleDbConnection do not have a common base class, but are implemented through the inherited interface IDbConnection. Now, a base class DbConnection is available, which is convenient, we can write database access code for the base class without paying attention to the specific database type, which facilitates the separation of the data access layer from the database ~ ② DataSet (DataTable) Optimization: the first is the new index engine. Let's take a look at the example: DataTable dt = new DataTable (); dt. columns. add ("field1"); dt. columns. add ("field2"); dt. primaryKey = new DataColumn [] {dt. columns [0]}; // This sentence is critical, otherwise it cannot be verified for (int I = 0; I <200000; I ++) dt. rows. add (new object [] {I, DateTime. now}); The above code is in. net1.1 execution requires 40 ~ 50 seconds; In. net2.0 runs for about 10 seconds, followed by real binary serialization. It serializes the above DataTable that contains 0.2 million records into a file: dt. remotingFormat = SerializationFormat. binary; // This is in. net1.1 does not have a System. runtime. serialization. formatters. binary. binaryFormatter bf = new System. runtime. serialization. formatters. binary. binaryFormatter (); System. IO. fileStream fs = new System. IO. fileStream (@ "D: \ test1.txt", System. IO. fileMode. createNew); bf. serialize (fs, dt); fs. close ();. net1. 1 is a file of about 29M size;. net2.0 is a file of about 7 m size; open it in notepad to see where the difference is. This is a good thing when you use Remoting to send a DataSet or able object. Finally, in ado. in net2.0, DataTable is more independent, and is not particularly dependent on DataSet as in the past. Sometimes, you have to put the DataTable in DataSet just to obtain a function, such as ReadXML () and WriteXMlSchema. ③ Some optimizations made for ms SQL Server, especially ms SQL Server2005: There are several topics: first, asynchronous processing of System. data. sqlClient. sqlCommand cm = new SqlCommand ("async = true ;..... "); System. IAsyncResult ar = cm. beginExecuteReader ();//..... // do other processingSystem. data. sqlClient. sqlDataReader dr = cm. endExecuteReader (ar); second, the System for optimizing mass data operations. data. sqlClient. sqlBulkCopy bcp = new SqlBulkCopy ("connection string"); bcp. writeToServer (myDataTable); 3 is in ADO. NET 2.0 for SQL Server 2005, multiple DataReader can be opened on the Command object at the same time

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: 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.