Changes from C ++ to C # Notes (4)

Source: Internet
Author: User

Introduction: every 10 years or so, programmers need to spend a lot of time and energy learning new programming technologies. In 1980s, it was Unix and C, and in 1990s it was Windows and C ++. Now it has reached Microsoft's. NETFramework and C #. Although new technologies need to be learned, the benefits are far higher than the labor cost. Fortunately, the analysis and design of most projects using C # And. NET have no essential changes in C ++ and Windows. In this article, I will introduce how to make a leap from C ++ to C.

Many articles have already introduced C #'s improvements to C ++, so I will not repeat these questions here. Here, I will focus on the biggest change from C ++ to C #: the change from an unmanageable environment to a manageable environment. In addition, I will make some mistakes that C # programmers can easily make for your reference. In addition, I will explain some new functions that C # can affect programming.

Series of articles: [changes from C ++ to C # Notes (1) (2) (3) (4)]

Read files from the network

In C ++, reading files on the network requires considerable programming skills. NET provides extensive support for this. In fact, reading files on the network is only another application of the Stream class in the base class library.

First, to listen to the TCP/IP Port (65000 in this example), we need to create an instance of the TCPListener class.


TCPListenertcpListener = newTCPListener (65000 );


Once created, let it start listening.


TcpListener. Start ();


Now we have to wait for the customer connection requirements.


SocketsocketForClient = tcpListener. Accept ();


The Accept method of the TCPListener object returns a Socket object. Accept is a synchronous method and will be returned only when a connection request is received. If the connection is successful, you can start to send files to the customer.


If (socketForClient. Connected)
{
???


Next, we need to create a NetworkStream class to pass the reporting path to constructor:


NetworkStreamnetworkStream = newNetworkStream (socketForClient );


Then create a StreamWriter object, but this time it is not on the file but on the NetworkStream class just created:


System. IO. StreamWriterstreamWriter =
NewSystem. IO. StreamWriter (networkStream );


When writing content to the stream, the stream is transmitted to the client over the network.

Client Creation

The client software is a specific example of a TCPClient class. The TCPClient class represents a TCP/IP connection to the host.


TCPClientsocketForServer;
Fig ("localHost", 65000 );


With the TCPClient object, we can create the NetworkStream object and then create the StreamReader class on it:


NetworkStreamnetworkStream = socketForServer. GetStream ();
System. IO. StreamReaderstreamReader =
NewSystem. IO. StreamReader (networkStream );


 

Now, the stream is read as long as there is data and the result is output to the console.


Do
{
OutputString = streamReader. ReadLine ();
If (outputString! = Null)
{
Console. WriteLine (outputString );
}
}
While (outputString! = Null );
 


To test the code, you can create a file for the next test:


Thisislineone
Thisislinetwo
Thisislinethree
Thisislinefour


This is the output from the server:


Output (Server)
Clientconnected
SendingThisislineone
SendingThisislinetwo
SendingThisislinethree
SendingThisislinefour
Disconnectingfromclient...
Exiting...


The output from the client is as follows:


Thisislineone
Thisislinetwo
Thisislinethree
Thisislinefour


Attributes and metadata

A significant difference between C # And C ++ is that it provides support for metadata: data of other entities such as classes, objects, and methods. Attributes can be classified into two categories: one type appears in the form of a part of CLR, and the other is an attribute created by ourselves. CLR attributes are used to support serialization, arrangement, and COM coordination. Some attributes are for a combination, while some attributes are for classes or interfaces. They are also called attribute targets.

Put the attribute in square brackets before the attribute target, and the attribute can act on their attribute target.


[Assembly: AssemblyDelaySign (false)]
[Assembly: AssemblyKeyFile (". \ keyFile. snk")]


Or use commas to separate the attributes:


[Assembly: AssemblyDelaySign (false ),
Assembly: AssemblyKeyFile (". \ keyFile. snk")]


Custom Attributes

You can create custom attributes at will and use them when appropriate. Assume that we need to track bugs and fix them. We need to create a database containing bugs, but we need to bind the bug report with the specific fixes, the following annotations may be added to the Code:


// Bug323fixedbyJesseLiberty1/1/2005.

In this way, you can clearly understand the bug fixes in the source code, but it may be better if you save the relevant information in the database, which makes it easier for us to query. It would be better if all the bug reports use the same syntax, but then we need a custom attribute. We may use the following content to replace the comments in the Code:


[BugFix (323, "JesseLiberty", "1/1/2005") Comment = "Offbyoneerror"]


Like other elements in C #, attributes are classes. Customized Attribute classes must inherit System. Attribute:


PublicclassBugFixAttribute: System. Attribute


We need to let the compiler know what type of elements this attribute can follow. We can specify this type of elements in the following way:


[AttributeUsage (AttributeTargets. ClassMembers, AllowMultiple = true)]


AttributeUsage is a metadata attribute that acts on an attribute. It provides metadata, that is, data about metadata. In this case, we need to pass two parameters. The first one is the target (in this example, it is a class member .), The second parameter indicates whether a given element can accept more than one attribute tag. The value of AllowMultiple is set to true, meaning that the class member can have more than one BugFixAttribute. To join two property targets, use the OR operator to join them.


[AttributeUsage (AttributeTargets. Class | AttributeTargets. Interface, AllowMultiple = true)]


The code above makes an attribute affiliated to a class or interface.

The new custom attribute is named BugFixAttribute. The naming rule is to add Attribute after the Attribute name. After assigning an attribute to an element, the compiler allows us to call this attribute using a simplified attribute name. Therefore, the following code is valid:


[BugFix (123, "JesseLiberty", "01/01/05", Comment = "Offbyone")]


The compiler first looks for the attribute named BugFix. If no attribute is found, it looks for the BugFixAttribute.

Each attribute must have at least one constructor. Two types of parameters are acceptable for attributes: Environment Parameters and named parameters. In the previous example, bugID, programmer name, and date are environment parameters, and annotations are named parameters. Environment parameters are passed to the constructor and must be passed in the order defined in the constructor.


PublicBugFixAttribute (intbugID, stringprogrammer, stringdate)
{
This. bugID = bugID;
This. programmer = programmer;
This. date = date;
}
Namedparametersareimplementedasproperties.
 


 

Related Article

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.