Rupeng Net learning notes (4). net common class libraries, learning notes. Net

Source: Internet
Author: User

Rupeng Net learning notes (4). net common class libraries, learning notes. Net

. Net Common Class Libraries

I. String member method (commonly used)
1. bool Contains (string str) determines whether the string object Contains the specified content.

2, bool StartsWith (String str): determines whether the String object starts with a given String.

3, bool EndsWith (String str): determines whether the String object ends with a given String.

Case: Determine whether the domain name is a Web site: It starts with http: // and ends with. com or. cn.

Case: Determine whether the email you entered is a QQ mailbox, and whether the user's user name contains sensitive words such as "Mao zidong ".

4. Use int Length to obtain the Length attribute of a string.

Str. Length

5, char ch = str [3];

6, int indexOf (int ch) // returns the index of the first occurrence of the specified character in this string

7, int indexOf (string str) // returns the index of the first occurrence of the specified string in this string

8, LastIndexOf // The last location

9, String Substring (int start) // truncates a String and returns the String truncated from the specified position

10, String substring (int start, int length) // truncates a String, returns a String with the specified length starting from the specified position

11, String ToLower () // converts the String to lowercase;

12, String ToUpper () // converts String to uppercase

13, String Replace (char oldChar, char newChar) // Replace the specified old character with the new character;

14, String Replace (string lodStr, string newStr) // use a new String to Replace the specified old string

15, String trim () // remove spaces at both ends of the String,

16, Trim (params char [] trimChars) // remove the given characters at both ends

17. TrimEnd and TrimStrat // remove the leading and trailing spaces.

18. String is immutable. Therefore, the preceding operations generate new String objects and use the returned values to receive new strings.

19, String [] Split () // There are many methods to overload, and strings are cut by separator.

Case: Use "," to separate strings

Ii. String static method

1, bool IsNullOrEmpty (string value) // determine whether the string is null or an empty string

2. bool Euqals (string a, string B, StringComparison. OrdinallgnoreCase) // compare the two strings in case-insensitive mode.

3, string Join (string separator, params string [] value) // concatenate an array (SET) into a string using the separator

Iii. StringBuilder

Because the string is immutable, A New String object will be generated when the string is connected, resulting in waste.  

1, Append ();
StringBuilder sb = new StringBuilder ();
Sb. Append (s1 );
Sb. Append (s2). Append (s3); // because the Append method returns this object (current object), you can perform chained programming.

Finally, use String s = sb. ToString () to generate the concatenation result String at a time.

2, AppendLine ();

Append the default line terminator to the end of the current System. Text. StringBuilder object. (After appending, press Enter)

4. Empty int

Int Is a value type and cannot be null. In C #, you can use int? Indicates an empty int"

Note:

Int? I = 5;
If (I! = Null)
{
Int i1 = (int) I; // forced conversion is required
}
You can also use I. HasValue to obtain the I value for both null and I. value.

We can see through IL that int? Actually translated by the compiler as Nullable <int> type

V. date type

DateTime indicates the time data type. Is a struct, so it is a value type.

DateTime. Now current time,

DateTime. Today current date

The Year, Month, and Hour attributes can be used to obtain the Year, Month, and Hour of the date;
You can also use constructors to create an object at a given time.

Vi. Concept of exceptions
The exception occurs when the program is abnormal. An exception is thrown as an exception class object. The exception class describes the exception information and location.

The root class of the Exception is Exception. Exception classes generally inherit from Excrption

VII. Exception capture

Try
{
String s = null;
S. ToString ();
}
Catch (NullReferenceException ex)
{
Console. WriteLine ("null" + ex. Message );
}

Ex is the exception class object, and the variable name is arbitrary as long as there is no conflict

In exception handling, once there is a problem in try. Discard the code after the try code block and directly jump to the catch to execute it.

If there is still code after try code, it will continue to be executed after catch is processed.


8. Handling Multiple exceptions
Try
{
Int a = 10;
Int B = 0;
Console. WriteLine (a/B );
Int [] arr = {1, 2, 3 };
Console. WriteLine (arr [3]);
}
Catch (DivideByZeroException AE)
{
Console. WriteLine ("the divisor cannot be 0 ");
}
Catch (IndexOutOfRangeException AE)
{
Console. WriteLine ("array out-of-bounds exception ");
}

You can catch exceptions of the parent class, so that you can catch exceptions of all sub-classes. However, it is strongly not recommended to do so. Do not catch exceptions with no reason.


9. Do not eat exceptions
Catch (Exception ex)
{
// Empty code
}

Do not just stop or print the exception catch. This is not a normal "Exception Handling"

If you do not know how to handle the error, do not catch it. It is better to "hide the error. In this way, I think that "no error will occur". In fact, the exception is "eaten" and the program will be in disorder.

Handle exceptions reasonably

10. finally

Try
{
// Code that may be faulty
}
Catch (exception type exception variable)
{
// Processing Method
}
Finally
{
// Code to be executed regardless of whether an exception occurs
}

In finally, resources are generally recycled.


11. File files

File is a static class (cannot be New), and its main static methods include:

1. void Delete (string path) deletes an object.

2. bool Exists (string path) checks whether the file Exists.

3, string [] ReadAllLines (string path) read the content of the text file to the string array

4. string ReadAllText (string path) reads a text file as a string

5. void WriteAllLines (string path, string [] contents) writes string [] to the file

6. void WriteAllText (string path, string contents) writes the string contents to the file path.

7. AppendAllText attaches content to the file

8. Copy the file

9. Move a file

12. Directory folder class, static class

1. CreateDirectory (string path): Create the full path of the folder

2, void Delete (string path, bool recursive)
Delete the folder path. recursive indicates whether to delete the sub-files and sub-folders.
If the folder is not empty and recursive is false, an exception is thrown.

Sample Code: Directory. Delete (@ "full path", true );

3. boolExists (string path) checks whether a folder exists.

4, Directory. EnumerateFiles (); returns the enumerated set of file names in the specified path.

5, Directory. EnumerateDirectories (); returns an enumerative set of Directory names that match the search mode in the specified path.

13. Stream

1. The File class provides a method for reading and writing text files. However, it cannot be used for large files. It occupies too much memory and requires a "stream processing" method.

2.. Net simplifies IO operations (files, networks, etc.) into Stream models. It is an abstract class,

Network, file, and encryption are different subclasses,

The most common subclasses are FileStream and MemoryStream.

3. When using Stream, you can:
FileStream fs = new FileStream ();
However, Stream fs = new FileStream (); better!

When the operations provided by the variable type can be met, declare variables with the parent class and interface as much as possible (reflecting the idea of polymorphism ),

4. FileStream writes files.

FileStream fs = new FileStream (@ "D: \ 1.txt", FileMode. Create); // Create a text file
Byte [] bytes = Encoding. Default. GetBytes ("Hello, such as Peng net"); // encode "Hello, such as Peng net" into a byte array object
Fs. Write (bytes, 0, bytes. Length); // operate on the fs object to Write
Fs. Close (); // Close the stream

The unit of Stream writing is byte. When char is converted to byte, an English char is converted to a byte (corresponding ASCII code), and a Chinese char is converted to two bytes.

The byte [] strings obtained using Default, UTF8, and UTF32 have different lengths. Therefore, different types of encodings are stored in different computers.

If you use any encoding to write data, you can use any encoding to read data. Otherwise, garbled characters may occur.

Note: Do not write data to drive C, because normal programs in Win7 and Win8 do not have the permission to read and write data to drive C by default.

5. FileStream reading

1, byte [] bytes = new byte [4];
When reading multiple bytes of data at a time, you cannot read a file at a time. Otherwise, the memory usage is too high because the array occupies the memory.
This is called a "buffer". The CPU is too small and the hard disk is very busy, and the memory is too large"

2, while (len = fs. read (bytes, 0, bytes. length)> 0) continue to read data of up to bytes Length from the stream and copy the data to the bytes array.
The next read operation starts from the last read location, and the read method returns the total number of bytes read this time (for example, the last read may fail ),
Once the = 0 value is returned, it indicates that the read is complete.
The initial value not assigned is 0, because the position of the unfilled array is 0.

3, String s = Encoding. Default. GetString (bytes, 0, len); converts byte [] to the corresponding string, considering that bytes is not fully utilized.

4. byte streams are not suitable for reading text files in the content, which may lead to data disorder (byte [] contains half of Chinese characters ).

Use StreamReader

14. Resource Closure

1. The above program has a defect. If an exception occurs during write, fs will not close, and other programs will not be able to write this file and will also occupy resources.

2. The resource must be used before it can be closed. Once it is closed, an error will occur.

3. The correct method is to put it in using () {}.




15th, using

1. Multiple resources can be declared at the same time.

Using (MyFile f1 = new MyFile ())
Using (MyFile f2 = new MyFile ())
{

}

2. using is actually a simplified try of the compiler .. Finally operation,

3. using is just try .. Finally: If catch is required, catch is the only method.

4. Note: Dispose is required when all the objects implementing the IDisposable interface are used up.


16. Copy files

1. Use two filestreams to copy files:
Read part of the content from the FileStream of the source file and write it to the FileStream of the target file.

Explanation code:
1, while (len = inStream. Read (bytes, 0, bytes. Length)> 0)
Return the length of the read result to len, and then judge the len value.

2, outStream. Write (bytes, 0, len );
Each write operation starts from the last position of the last write operation. Write byte [] array B to outStream. The off code is the offset from the current write position. Generally, write 0. len indicates the length of write.
Set the buffer zone to 50 and change it to 1 MB to see the speed change. Use the StopWatch class for code timing.


2. encapsulate a Copy method
Encapsulate a void copy (Stream inStream, Stream outStream, int bufferSize) function to copy inStream to outStream,
The buffer size is bufferSize. Check the validity of the parameter (whether it is null or whether bufferSize is in a reasonable range)


3. A CopyTo method is provided in the Stream class after. Net 4.0.


4. Reader and Writer (text content)

Directly Using Stream to read and write text files is troublesome, because the file encoding and Chinese characters need to be considered.

StreamReader and StreamWriter are classes used to read and write the character stream (characterstream), which will help automatically solve troublesome problems.


VII. Encoding

1. for historical reasons, there are many standards on how to store Chinese Characters in bytes in computers. The most common are GB2312 (national standard, Indicating Chinese characters ),
GBK (GB2312 extension, also can express traditional Chinese characters, etc.), UTF-8 (International Standard), UTF-16, etc.

2. ANSI indicates that the default encoding of the current operating system is used. For Windows in Chinese, the default encoding is GBK.

3. No garbled characters will be generated if any encoding is used for storage.

4. How do I save it with other codes? Determined by the StreamWriter constructor: new StreamWriter (outStream, Encoding. UTF8
How can we preliminarily determine the encoding used? Open notepad and save it as. You can see

5. The read encoding is determined by the StreamReader constructor.

18. Generic container List <T>

1. the array length is fixed. List <T> can dynamically add or delete content.

List <T> is generic. You can specify the type of data to be stored during the declaration.

2. How to add

List <int> list = new List <int> ();

List. Add (1 );

List. Add (2 );

List. AddRange (new int [] {1, 2, 3, 4, 5 });

List. AddRange (list2); // Add another list

3. How to traverse

Int [] nums = list. ToArray (); // The List generic set can be converted to an array.

List <string> listStr = new List <string> ();

String [] str = listStr. ToArray ();

19. Generic Dictionary <Key, Value>

1. How to add
Dictionary <string, string> dict = new Dictionary <string, string> ();
Dict. Add ("zs", "Zhang San ");
Dict. Add ("ls", "Li Si ");
Dict. Add ("ww", "Wang Wu ");

2. How to modify
Dict ["ls"] = "Xiao Zhao ";
String s = dict ["ww"];

3. determine whether or not to include
Dict. ContainsKey ();

20. foreach

1. In addition to the for loop, the objects that implement the IEumerable interface can also be traversed using foreach.

String [] strs = {"asdasd", "qweqweq", "gdfg "};
Foreach (string s in strs)
{
Console. WriteLine (s );
}

2. List <T>, Dictionary <K, V>, and other objects that implement the IEnumerable interface can be traversed.

Dictionary <string, object> dict = new Dictionary <string, object> ();
Dict ["rupeng"] = 888;
Dict ["sina"] = "hehe ";
Dict ["baidu"] = true;
Foreach (KeyValuePair <string, object> kv in dict)
{
Console. WriteLine (kv. Key + "=" + kv. Value );
}

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.