In those years, I am still studying C #.
In those years, learning C # is to have an understanding of some C # related knowledge. It will not be able to find any direction until it is necessary. For example, how can I feel useless at the beginning of the expansion method, later I learned about asp.net MVC, which can be used to expand Html classes, for example, to create a paging method. Therefore, it is no harm to know a wide language; C # is not mentioned above, such as file reading, network (socket) programming, serialization, etc. They are all very important. Let's take a look!
I. Reading files
When learning to read files, we generally refer to byte streams and bytes streams, which are read by byte before and by character. We use FileStream, StreamWriter, StreamReader, BinaryWriter, and BinaryReader, in System. i/O space provides their use, reading files is not only useful in desktop programs, but also useful in asp.net web programs. By reading files, you can generate static web pages, some pages that do not require interaction can be made static pages, such as news. Let's take a look at how to use them:
1. Use of StreamWriter and StreamReader:
Copy codeThe Code is as follows: // <summary>
/// Writer reads the file through the path and writes data
/// </Summary>
/// <Param name = "path"> path </param>
Public void FileOpOrCreateWriter (string path)
{
// Open or create a file
Using (FileStream fs = new FileStream (path, FileMode. OpenOrCreate ))
{
// Write data to the Open File
Using (StreamWriter sw = new StreamWriter (fs, Encoding. UTF8 ))
{
// Write data
Sw. WriteLine ("my name is whc ");
Sw. Flush ();
}
}
}
/// <Summary>
/// Reader reads the file
/// </Summary>
/// <Param name = "path"> path </param>
Public void FileOpOrCreateReader (string path)
{
Using (FileStream fs = new FileStream (path, FileMode. OpenOrCreate ))
{
Using (StreamReader sr = new StreamReader (fs, Encoding. UTF8 ))
{
Console. WriteLine (sr. ReadLine ());
}
}
}
2. BinaryWriter and BinaryReaderCopy codeThe Code is as follows: // <summary>
/// Writer binary Writing Method
/// </Summary>
/// <Param name = "path"> </param>
Public void FileOpOrCreateBinaryWriter (string path)
{
Using (FileStream fs = new FileStream (path, FileMode. OpenOrCreate ))
{
Using (BinaryWriter bw = new BinaryWriter (fs, Encoding. UTF8 ))
{
String myStr = "this is a Good boy China !!! ";
// Obtain the binary code of the string
Byte [] bt = new UTF8Encoding (). GetBytes (myStr); // UTF8Encoding (). GetBytes (myStr );
Console. WriteLine ("binary:" + bt + ", size:" + bt. Length );
Bw. Write (bt );
Bw. Flush ();
}
}
}
/// <Summary>
/// BinaryReader reads data
/// </Summary>
/// <Param name = "path"> </param>
Public void FileOpOrCreateBinaryReader (string path)
{
Using (FileStream fs = new FileStream (path, FileMode. OpenOrCreate ))
{
Using (BinaryReader br = new BinaryReader (fs, Encoding. UTF8 ))
{
Char [] myStr = new char [1024];
// Obtain the binary code of the string
Byte [] bt = br. ReadBytes (1024 );
// Decoding
Decoder d = new UTF8Encoding (). GetDecoder ();
D. GetChars (bt, 0, bt. Length, myStr, 0 );
Console. WriteLine (myStr );
}
}
}
3. Other File OperationsCopy codeThe Code is as follows: // <summary>
/// Delete an object
/// </Summary>
/// <Param name = "path"> </param>
Public void DeleteFile (string path)
{
Try
{
File. Delete (path );
}
Catch (Exception e)
{
Console. WriteLine ("It is errors ");
}
}
/// <Summary>
/// Display files in the directory
/// </Summary>
/// <Param name = "path"> </param>
Public void getDirectorInfo (string path)
{
// Obtain the Directory
String [] fileNameList = Directory. GetDirectories (path );
For (int I = 0; I <fileNameList. Length; I ++)
{
Console. WriteLine (fileNameList [I]);
FileInfo fi = new FileInfo (fileNameList [I]);
Console. WriteLine ("file name:" + fi. FullName );
Console. WriteLine ("File Creation Time:" + fi. CreationTime );
Console. WriteLine ("last access time:" + fi. LastAccessTime );
}
}
Ii. serialization
Serialization in C # is also called serialization. the operating environment of the. net platform supports the streaming mechanism of user-defined types. Its function is to store objects in a certain situation for persistence, or to transmit objects over the network, which can be stored in files or databases, the application can read the last saved state at the next startup to share data in different programs. Its main functions are as follows:
1. Read the information of the last saved object at the next startup of the process.
2. Transmit data between different AppDomains or processes
3. Data Transmission in Distributed Application Systems
. NET provides three methods to serialize an object:
1. Binary: BinaryFormatter. You can use the IFormatter interface to using System. Runtime. Serialization. Formatters. Binary;
Serialize the object to binary. The Code is as follows:
Copy codeThe Code is as follows: // <summary>
/// Serialize an object to the memory
/// </Summary>
/// <Param name = "obj"> </param>
/// <Returns> </returns>
Private byte [] Serializable (SerializableObj obj)
{
IFormatter ifmt = new BinaryFormatter ();
Using (MemoryStream MS = new MemoryStream ())
{
Ifmt. Serialize (MS, obj );
Return ms. ToArray ();
}
}
2. SoapFormatter using System. Runtime. Serialization. Formatters. Soap; IFormatter interface can be used to add the corresponding assembly.
Soap is a simple object access method. It is a lightweight, simple, XML-based protocol designed to exchange structured and solidified information on the WEB.
SOAP can be used in combination with many existing Internet protocols and formats, including Hypertext Transfer Protocol (HTTP), Simple Mail Transfer Protocol (SMTP), and multi-purpose Internet Mail Extension protocol (MIME ).
It also supports a large number of applications from the message system to Remote Process calling (RPC. SOAP uses a combination of XML-based data structures and Hypertext Transfer Protocol (HTTP) to define a standard method to use distributed objects in different operating environments on the Internet .)
The Code is as follows:
Copy codeThe Code is as follows: // <summary>
/// Deserialize an object in memory
/// </Summary>
/// <Param name = "byteData"> </param>
/// <Returns> </returns>
Private SerializableObj DeSerializable (byte [] byteData)
{
IFormatter ifmt = new SoapFormatter ();
Using (MemoryStream MS = new MemoryStream (byteData ))
{
Return (SerializableObj) ifmt. Deserialize (MS );
}
}
3. XML Serialization of using System. Xml. Serialization;. XmlSeralizer requires the class to have a default constructor.
Copy codeThe Code is as follows: XmlSerializer xsl = new XmlSerializer (typeof (SerializableObj ));
Using (MemoryStream MS = new MemoryStream (byteData ))
{
Return (SerializableObj) xsl. Deserialize (MS );
}
We can use these methods to complete the required serialization.
At the same time, when specifying classes, we can also use features to describe what needs to be serialized and what does not need to be serialized, as shown below:Copy codeCode: [Serializable] // serialization required
Class SerializableObj
{
[NonSerialized] // serialization not required
Public int OrderId;
Public string OrderName;
Public SerializableObj (){}
Public SerializableObj (int OrderId, string OrderName)
{
This. OrderId = OrderId;
This. OrderName = OrderName;
}
Public override string ToString ()
{
Return "OrderId:" + OrderId + "\ t \ nOrderName:" + OrderName;
}
}
4. Custom serialization
You can use the ISerializable interface to customize serialization and implement the GetObjectData () method:Copy codeThe Code is as follows: class CumstomSerializable: ISerializable
{
Public void GetObjectData (SerializationInfo info, StreamingContext context)
{
Throw new NotImplementedException ();
}
}
3. Learning from Linq
Linq is a new feature added to C #3.0. In order to make the query easier, you can also perform operations on the set, making the operations on the database and set easier, such: in the format of "from" and "select clause" or "group by clause.
1. Keywords in Linq
· From: Specifies the variable (range variable) that the data source uses to iterate the data source)
· Where: Filter query results
· Select: Specifies the items in the query results.
· Group: Aggregates related values through a keyword.
· Into: stores aggregate results or connects to a temporary variable
· Orderby: the query results are listed in ascending or descending order by a keyword.
· Join: connect two data sources with a keyword
· Let: create a temporary variable to represent the subquery results.
2. Methods of the System. Linq. Enumernable class
· Aggregate (): applies the same function to each item in the sequence.
· Average (): returns the Average value of each item in the sequence.
· Count (): returns the total number of items in a sequence.
· Distinct (): return different items in the sequence
· Max (): returns the maximum value in the sequence.
· Min (): returns the minimum value in the sequence.
· Select (): return certain items or attributes in the sequence.
· Single (): returns a Single value in the sequence.
· Skip (): skips the specified number of items in the sequence and returns the remaining elements.
· Take (): returns the exponential target element in the sequence.
· Where (): filter elements in a sequence
· OrderBy (): returns the results of sorting a specific field in ascending order.
· OrderByDescending (): returns the query results sorted in descending order of a specific field.
· ThenBy (): returns the query results sorted by an additional field.
· ThenByDescending (): returns the query results sorted in descending order using an additional field of cream.
· SingleOrDefault (): select a single row or default instance.
· Skip (): allows skipping a specified number of records
· Take (): a certain number of records are allowed.
4. Example:Copy codeThe Code is as follows: List <string> linqList = new List <string> (){
"Demo1", "Demo2", "Demo3"
};
// SCSI is a range variable and where is a condition. It looks like an SQL statement.
IEnumerable <string> results = from SCSI in linqList where SCSI. Contains ("2") select SCSI;
Foreach (var result in results)
{
System. Console. WriteLine (result. ToString ());
}
Result: Demo2
The System will be called when the Linq query is translated. linq. the method of the Enumernable class, which translates the Linq statement into a query statement and a query method: var demo = linqList. where (m => m. contains ("2 ")). select (m => m); the result is the same as above
Summary:
Those years of learning C # mainly focus on learning some of its basic knowledge. At the same time, it is also better to use C # for programming in asp.net web development, this article will recall the days when I learned C # in those years.