In those years I was still learning C

  • 2020-05-07 20:16:23
  • OfStack

In those years, I was still learning C# continuation
During those years, I learned C#, which means that I had an understanding of some knowledge related to C#, and I would not lose my direction when I needed to use it. For example, I felt that extending methods was useless at first, but later I learned that asp.net MVC can be used to extend Html class, such as doing a pager method. So it doesn't hurt to know more about a language; There are also 1's in C# that were not mentioned above, such as: reading files, network (socket) programming, serialization, etc., they are very important, ah, let's take a look at 1!
1. Read the file
In the file reading learning, 1 will generally mention the byte stream and character stream, read by byte before, read by character after; We through FileStream, StreamWriter, StreamReader, BinaryWriter, BinaryReader to complete, in System. IO provides their use in the space, read a file operation is not only useful in the desktop application, and in asp. net web is also useful in the program, by reading files can generate static pages, some don't need to interact with page 1, can be made into a static page, such as news. Here's how to use them:
1. Use of StreamWriter and StreamReader:
 
/// <summary> 
/// Writer The file is read by path , And write data  
/// </summary> 
/// <param name="path"> The path </param> 
public void FileOpOrCreateWriter(string path) 
{ 
// Open or create 1 A file  
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate)) 
{ 
// Writes data to an open file  
using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) 
{ 
// Write data  
sw.WriteLine("my name is whc"); 
sw.Flush(); 
} 
} 
} 
/// <summary> 
/// Reader Read the file  
/// </summary> 
/// <param name="path"> The 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. Use of BinaryWriter and BinaryReader
 
/// <summary> 
/// Writer2 Base write 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 !!!"; 
// Get the string 2 System code  
byte[] bt = new UTF8Encoding().GetBytes(myStr); //UTF8Encoding().GetBytes(myStr); 
Console.WriteLine("2 Into the system for :" + bt + ", The size of the :" + bt.Length); 
bw.Write(bt); 
bw.Flush(); 
} 
} 
} 
/// <summary> 
/// BinaryReader Read the 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]; 
// Get the string 2 System code  
byte[] bt = br.ReadBytes(1024); 
// decoding  
Decoder d = new UTF8Encoding().GetDecoder(); 
d.GetChars(bt, 0, bt.Length, myStr, 0); 
Console.WriteLine(myStr); 
} 
} 
} 

3. Other operations of the file
 
/// <summary> 
///  Delete the file  
/// </summary> 
/// <param name="path"></param> 
public void DeleteFile(string path) 
{ 
try 
{ 
File.Delete(path); 
} 
catch (Exception e) 
{ 
Console.WriteLine("It is errors"); 
} 
} 
/// <summary> 
///  Displays the files in the directory  
/// </summary> 
/// <param name="path"></param> 
public void getDirectorInfo(string path) 
{ 
// Get the directory under 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("  The file name :" + fi.FullName); 
Console.WriteLine("  File creation time :" + fi.CreationTime); 
Console.WriteLine("  Last access time :" + fi.LastAccessTime); 
} 
} 

2. The serialization
In c # serialization, also known as serialization is. net platform running environment support user-defined types of fluidization mechanism, its role in certain situation storage object persistence, or in the network transmission, can be stored in a file, or database, the application can start my next read once saved on mode shape, so that in different applications to share data with, its main function is as follows:
1. Read the information of the last saved object the next time the process starts
2. Passing data between different AppDomain or processes
3. Transfer data in distributed application system
NET provides three ways to serialize an object, mainly:
1, 2, hexadecimal, BinaryFormatter, can use IFormatter interface to use it using System. Runtime. Serialization. Formatters. Binary;
Serialize the object to base 2, the code is as follows:

 
 /// <summary> 
///  serialization 1 Objects into 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, SoapFormatterusing System. Runtime. Serialization. Formatters. Soap; When the IFormatter interface is not available, the corresponding assembly can be added
The Soap approach is a simple form of object access, a lightweight, simple, XML-based protocol designed to exchange structured and hardened information on WEB.
SOAP can be used in conjunction with many existing Internet protocols and formats, including the hypertext transfer protocol (HTTP), the simple mail transfer protocol (SMTP), and the multipurpose Internet mail extension protocol (MIME).
It also supports a wide range of applications, from messaging systems to remote procedure calls (RPC). SOAP defines a standard way to use distributed objects in various operating environments on Internet using a combination of XML-based data structures and the hypertext transfer protocol (HTTP).
The code is as follows:

 
/// <summary> 
///  deserialization 1 Two objects 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 serializes using System. Xml. Serialization; .XmlSeralizer requires classes to have a default constructor

 
XmlSerializer xsl = new XmlSerializer(typeof(SerializableObj)); 
using (MemoryStream ms = new MemoryStream(byteData)) 
{ 
return (SerializableObj)xsl.Deserialize(ms); 
} 

We can do the required serialization in each of these ways
At the same time, when we specify the class, we can also specify what needs to be serialized and what doesn't, as follows:
 
[Serializable]// Need to serialize  
class SerializableObj 
{ 
[NonSerialized] // No serialization 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
Custom serialization can be customized by using the ISerializable interface and implementing the GetObjectData() method, as follows:
 
class CumstomSerializable:ISerializable 
{ 
public void GetObjectData(SerializationInfo info, StreamingContext context) 
{ 
throw new NotImplementedException(); 
} 
} 

3. Linq learning
linq is a new feature of C#3.0. In order to make the query easier, it can also operate on the collection, making the operation of the database and the collection easier, such as: Linq to sql, Linq to dataset, Linq query expression starts with "from", and ends with a "select clause "or "group by clause".
1. Keywords in Linq
· from: specify the data source to be used to iterate over the data source variables (scope variables)
· where: filter query results
· select: specifies the item in the query result
· group: related values are aggregated by a certain keyword
· into: stores the results in the aggregation, or connects to 1 temporary variable
· orderby: query results are listed in ascending or descending order according to a keyword
· join: connect the two data sources with one keyword
· let: create a temporary variable to represent the result of the subquery
2, System. Linq. Enumernable class method
· Aggregate(): apply 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 the sequence
· Distinct(): returns the different items in the sequence
· Max(): returns the maximum value in the sequence
· Min(): returns the minimum value in the sequence
· Select(): returns some items or attributes in the sequence
· Single(): returns a single 1 value in the sequence
· Skip(): skips the sequence to specify the number of items and returns the remaining elements
· Take(): returns the exponential destination element in the sequence
· Where(): filters the elements in the sequence
· OrderBy(): returns the result of an ascending sort for a specific field
· OrderByDescending(): returns the query results sorted in descending order by a specific field
· ThenBy(): returns the result of a query sorted with an extra field
· ThenByDescending(): returns the results of a query sorted in descending order using frost 1 extra fields
· SingleOrDefault(): select a single line or the default instance
· Skip(): allows you to skip a specified number of records
· Take(): a fixed number of records is allowed
4. Examples:
 
List<string> linqList = new List<string>() { 
"Demo1","Demo2","Demo3" 
}; 
//lq is 1 Range variables, where It's the condition. It looks similar SQL statements  
IEnumerable<string> results = from lq in linqList where lq.Contains("2") select lq; 
foreach (var result in results) 
{ 
System.Console.WriteLine(result.ToString()); 
} 

Results: Demo2
When Linq query is translated, the method of System.Linq.Enumernable class is called to translate Linq statement into query statement and query method :var demo = linqList.Where (m = m) > m.Contains("2")).Select(m = > m); The same as above
Conclusion:
Learning C# in those years was mainly about learning the basics of asp.net web, but also about programming C# better when asp.net web was developed.

Related articles: