C #2.0 syntax changes

Source: Internet
Author: User
Document directory
  • C #2.0 syntax changes:
  • Data Access
C #2.0 syntax changes:

① Generic:

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 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, which can be well known during class instantiation.
Stack <int> AAA = new stack <int> ();
The Int type can only be placed in the stack, for example, AAA. Push (17;
However, 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. I will not explain them 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
Where T: B // t inherited from B
{......}

② Anonymous method and iterator;

There is nothing to do with the anonymous method. Compare the two sections of the Code in the example to see the following:
(C #1.0 ):
Button1.click + = new eventhandler (button#click );
Private void button#click (Object sender, eventargs E)
{
Textbox1.text = "123 ";
}
With the anonymous method (C #2.0 ):
Button1.click + = delegate {
Textbox1.text = "123 ";
}
To be honest about the anonymous method, I think it is just to save a few lines of code and handle the delegate more conveniently. It is just a "trick" of the C # compiler ......

Then there is the "iterator ":
If you need to create a set (which can be used for the foreach loop) without such a collection
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 the "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];
}
}
It's relatively simple. You can see that there are two places that are a little fresh:
1) added the yield keyword;
2) use the iterator to create reverse traversal:
Public ienumerable <t> bottom totop {
Get {
For (INT I = 0; I <count; I ++> ){
Yield return items [I];
}
}}

③ Segment type definition:

The Division type allows us to divide a class, structure, or interface into several parts and implement them in several unused. CS files. 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.

The following is an example of simple code:
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 empty, 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 needs to be executed in. net1.1 from 40 ~ 50 seconds; it takes about 10 seconds to run in. net2.0

Second, real binary serialization;

Serialize the above datatable containing 0.2 million records into a file:

DT. remotingformat = serializationformat. Binary; // This is not available in. net1.1.
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:
The first is asynchronous processing.
System. Data. sqlclient. sqlcommand CM = new sqlcommand ("async = true ;.....");
System. iasyncresult AR = cm. beginexecutereader ();
//.....
// Do other processing
System. Data. sqlclient. sqldatareader DR = cm. endexecutereader (AR );

Second, optimization of Mass Data Operations
System. Data. sqlclient. sqlbulkcopy BCP = new sqlbulkcopy ("connection string ");
BCP. writetoserver (mydatatable );

Third, for SQL Server 2.0 in ADO. NET 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: 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.