Common class libraries. NET in the string
Characteristics of strings
1. immutability Because the string is immutable, each time the string is modified, a separate copy of the string is created (a copy of the string is copied). The change is only because it points to a new address.
2. String pool (for string constants only) when there are multiple identical string constants in a program, multiple variables point to the same piece of string in memory! This feature is called a string pool. The reason the string does not cause confusion in the program is because of the immutability of the string.
Member methods and properties of string
PS: There are many overloaded ways, not listed.
1.Contains (String str) determines whether the string is contained, specifying a string.
Usage
String str = "HelloWorld";
Str. Contains ("Hello"); True
2.StartsWith (String str)
Determines whether the string object begins with a specified string.
3.EndWith (String str)
Determines whether the string object ends with a specified string.
4.Length Properties
Gets the length of the string
5.IndexOf (String str)
Gets the specified character/string ... The position of the first occurrence in the object string.
6.LastIndexOf (String str)
Gets the specified character/string .... The position that appears last in the object string.
7.SubString (int start)
SubString (int strat, int length) intercepts the string from the specified position.
8.ToLower ()
Converts the string to lowercase, returning a new all-lowercase character.
9.ToUpper ()
Converts the string to uppercase, returning a new all-uppercase character.
Replace (String oldstr,string newstr)
Replaces the old string part of the object string with a new string.
11.Trim () remove spaces at both ends of the object string
TrimStart () Remove space at the beginning of the object string
TrimEnd () Remove space at the end of the object string
PS: Other overloads of Trim () can be used if you want to strip other characters of other characters at the end of the opening.
12.Split () splits the object string into an array of strings, according to the specified characters!
The overloads of Split () are also many,
For example, Split (new char[]{' | '}, stringsplitoption.removeemptyentries)//Delete empty data
static method of String
1.IsNullOrEmpty (String)
String. IsNullOrEmpty (STR1) determines whether a string is null, or is an empty string.
2.Equals (String,string,stringcomparison.ordianlignore) ignores case comparison of two strings.
3.Join (string,string[]) stitch an array into a string by the specified string.
. NET Timer Control TimerThis chapter introduces some superficial ways to use the Timer control. Describes common properties and events for a timer control
1. The Interval property represents the time interval for the timer control.
The type is int by default is milliseconds.
2. The Enabled property indicates whether the timer control is active.
If activated, a tick event that enters the timer starts executing. So the default is False
3. Start () method
Start execution
4. Stop () method
Stop execution
5. Tick Events
Represents the code that the Timer control will execute.
General use Mode
1. Add a Timer control
2. after setting the necessary properties. Write the Timer_tick event directly. It would be nice to write a stop condition in the event.
Invoking a timer using a lambda expression
Timer timer = new timer ();
Timer. Interval = 100;
Using lambda expressions
Timer. Tick + = (sender,e) =
{
if (Blah)
{
Timer. Stop ();
}
};
Timer. Start ();
. NET in the StringBuilderWhy to use StringBuilder
Why use StringBuilder to start with the properties of a string object.
String object concatenation, because the character string is immutable, the string object will be duplicated every time, will copy a copy out of the operation, and its own strings remain in memory, a large number of temporary fragments will cause negligible performance loss. So it is recommended to use StringBuilder when doing a lot of string stitching
The simple way to use StringBuilder
string S1 = "33";
String s2 = "44";
String s3 = "55"; The demand is to S1 S2 S3 together. This is a typical string concatenation.
With StringBuilder, no useless temporary strings are generated.
StringBuilder SB =new StringBuilder ();
Stitching method One
Sb. Append (S1);
Sb. Append (S2);
Sb. Append (S3);
//splicing mode two
Because the Append () method returns a This, which is the object itself. So you can use this method.
Chained programming jquery is commonly used in this way
Sb. Append (S1). Append (S2). Append (S3);
Finally put SB. ToString () Just a little bit better.
The Ps:appendline () method can automatically add a carriage return.
datetime in. NETAbout DateTime
datetime is a time type in. NET that allows you to perform operations such as getting the current system time through DateTime. DateTime is a struct in. NET, not a class.
As shown, this icon represents the struct in vs.
Common methods and members for DateTime
1.Now Gets the current system time. Format as
2.Today Gets the current today's date. Format as
3. Month and day seconds the next few objects must be referenced by DateTime.Now (or Datetime.today). Year gets the Hour gets the hour month gets the month Minute gets the minute day gets the date Second gets the second
Take year as an example: DataTime.Now.Year
4.DayOfWeek, DayOfYear Get the current date is the day of the week
And getting the current date is the day ordinal of the year
5.TryParse () determines whether it is a time type, with an out parameter that can output a DateTime object.
6.AddDays (), AddHours ()
Add a few days to the current time to return a datetime based on the current date add a few hours to return a datetime
7.Subtract (datetime.now)
Compare two time difference returns a TimeSpan
Date Time format character ToString ()
pre-defined modeDateTime date =datetime.now; Date. ToString (
format) parameter
formatFormat verbose usage Format Character Association properties/Description D ShortDatePattern d longdatepattern f full date and time (long date and short time) F Fulldatetimepattern (long date and long time) G regular (short date and Short time) G regular (short date and long time) m, M Monthdaypattern R, R rfc1123pattern s using local time Sortabledatetimepattern (based on ISO 8601) T SHORTTIMEP Attern T longtimepattern u universalsortabledatetimepattern used to display the format of the Universal Time U use the full date and time of the universal Time (long date and long time)
Y, y Yearmonthpattern
Custom ModeA day in the D month. One-digit date has no leading zeros. DD a day of the month. A one-digit date has a leading zero. The abbreviated name of the day of the DDD week, defined in Abbreviateddaynames. dddd the full name of the day of the week, as defined in DayNames. M-month number. One-digit month has no leading zeros. MM month number. One-digit month has a leading zero. Abbreviated name of the MMM month, defined in AbbreviatedMonthNames. The full name of the MMMM month, as defined in MonthNames. Y does not contain the year of the era. If the year that does not contain an era is less than 10, the year is displayed without leading zeros. YY does not contain the year of the era. If the year that does not contain an era is less than 10, the year with leading zeros is displayed. The YYYY includes the four-digit year of the era. GG period or ERA. If the date to be formatted does not have an associated period or era string, the pattern is ignored. H 12 Hour hour system. One-digit hours do not have leading zeros. HH 12-hour hour. One-digit hours have leading zeros. H 24 hour hour system. One-digit hours do not have leading zeros. HH 24-hour hour. One-digit hours have leading zeros. M minutes. A single-digit number of minutes does not have a leading zero. MM minutes. A single-digit number of minutes has a leading zero. s seconds. The number of seconds in a single digit does not have a leading zero. SS seconds. The number of seconds of one digit has a leading zero.
. NET exceptions and exception handling. NET exceptions (Exception)
The parent class of the exception in. NET is exception, and most exceptions generally inherit from exception.
You can customize the exception class by writing a class that inherits from Exception!
Exception handling mechanism
Try
{
Code that might have occurred an exception
Subsequent code
}
Code outside of Try
catch (Exception e)
{
}
Finally
{
}
The above code is described below
1. Who can perform in exception handling, once a try has a problem, the program discards the exception's subsequent code and jumps directly into the catch.
Executes the code in the catch and resumes execution of code other than the try.
2. About the parameter in catch () E
E is the exception class object that occurs, can be arbitrarily named. Not must be called E.
3. Throw only one
The code in a try can only throw an exception.
Why is it?
Because once the exception is thrown, ah, there is no implementation of the back!
4. Access to Information
Exception information can be obtained by e.message
5. must perform
Finally it will be executed anyway
6. Can not catch
Can be only try Catch
You can also have only try finally
Excellent style of exception handling
1. do not avoid the problem not only catch the exception, do nothing, or just print it, this is not a good "exception handling" style.
Do not catch if you do not know how to handle the exception. Expose him to it. Since there is an exception, the problem is certain, escape is not a way to face him, to solve him. Especially in layered projects. Causes the program to fall into a state of deep logic chaos. And the problem is hidden, and you don't even know where it's going to go wrong.
2. What if you really encounter a random try, catch programmer?
VS is very powerful, and it's thinking of this. Click "Debug" "Exception" to enter such a tool, select the second row of the Raise option.
This way, when debugging, whether or not the try catch will burst out of the exception. The information we wanted was found.
. An introduction to IO Operations Basics in netAbout IO Introduction
. NET IO operations, it is often necessary to call several classes.
1.FileStream class
File Stream class, responsible for large file copy, read and write.
2.Path Class
The method in the path class is basically an operation on a string (file name) and does not matter much to the actual file.
3.File Class
the file class can make some copies of small files, cut operations, and can read some document files.
4.dirctory
directory operations, create files, delete directories, get directories under file names, and so on.
Path class
1.changeextension (path, ". jpg")
Change the file suffix name!
2.Combine (S1,S2)
Connect two paths to each other.
3. Several ways to get the file name
1) path.getfilename (S1); Gets the file name in the path
2) path.getfilenamewithoutextension (S1); Get the file name, not including the suffix name!
3) Path.getdirectoryname (S1)//Gets the directory in the path does not include the file name.
4) path.getextension (S1); Get extension only
4.GetFullPath ("")
Gets the full path and obtains the absolute path based on the relative path.
5. Temp directory
1) GetTempPath ()//Get the temporary directory of the current user
2) GetTempFileName ()//Get a random file name and create this file in the temp directory.
3) Getrandomfilename ()//Get only one random file name.
Directory Class
1. Create a directory
Directory.CreateDirectory (@ "directory");
2. determine if a file exists in a directory
string path [email protected] "path";
if (directory.exists (path))
{
}
3. Deleting a directory
1) directory.delete (path); Delete Empty directory, there is no file in the directory.
2) Directory.delete (path,true); Whether empty or not, all delete!
3) If there is no directory to report the exception, it is best to use if (path) to determine directory.exists.
4. Move the file directory
Renaming the directory is also done with this.
Directory.move (@ "c:\a", @ "C:\ABC");
5.DirectoryInfo
You can use the folder as an object.
DirectoryInfo dirinfo = new DirectoryInfo (@ "path");
6. Get all immediate subdirectories and direct sub-files under the current directory
Get the immediate subdirectory under the directory
String[] dirs =direcotory.getdirectories (@ "directory");
Get direct sub-file under directory
String[] Files =directory.getfiles (@ "directory");
7. get the directory and file under the current directory another way
Get the immediate subdirectory under the directory
String[] dirs =direcotory.getdirectories (@ "directory");
Get direct sub-file under directory
String[] Files =directory.getfiles (@ "directory");
————————— above is 6 in the practice, he has a certain performance problems. What's the problem? —————————————
Use string[] dirs =direcotory.getdirectories (@ "directory"); It is necessary to wait for the entire string to traverse the collection.
If desired, read one of the processing lines.
Recommended use of Directory.enumeratefile ()
1) Enumeratefile Returns a collection that implements the IEnumerable interface. The iterator pattern is actually used.
2) The Searchoption.alldirctories parameter will allow. Enumeratefile () to traverse files in all subdirectories.
File class
1. Copy
File.Copy ("Source", "Target", true);
2. Determine if there is
File.exists (@ "Source");
3. cut
File.move ("Source", "Targe");
4. Create
File.create ("path");
5. Delete
File.delete ("path"); Delete, if not, do not error!
6. read operation
1) file.readalllines ("path", Encoding.default); Returns a string[]
2) file.readalltest ("path", Encoding.default); String
3) file.readallbytes ("path");
7. Write operations
1) file.writealllines ("Path", new String[4],encoding.default);//write to a file by line.
2) File.writealltext ("Path", "string");
3) file.writeallbytes ("Path", new Byte[4]);
4) File.appendalltext (); Appends a string to the file.
8. return a shortcut to FileStream
1) File.Open (String,filemode); Returns a FileStream
2) File.openread (String,filemode); Returns a read-only FileStream
3) File.openwrite (String,filemode); Returns a write-only FileStream
. NET IO operations in the file streamRead operation
1. Create a file stream
FileStream fsread =new FileStream ("1.txt", FileMode.Open);
2. Create a buffer that, under normal circumstances, is not directly equal to the file size. It's only read here, so it's done.
byte[] bytes =new byte[fsread.length];
3. Start reading, the return value is the length of the read.
int r =fsread.read (bytes,0,bytes. Lenght);
4. Turn off the release stream
Fsread.close ();
Fsread.dispose ();
Write operations
1. Creating a written file stream
FileStream fswrite fswrite =new FileStream (@ "xxx", filemode.openorcreate);
2. Creating buffers
String msg = "HelloWorld";
Byte[] bytes =enconding.utf8.getbytes (msg);
3. Start writing
Fswrite.write (bytes,0,bytes. Length);
4. Close
Fswrite.close ();
Fswrite.dispose ();
Conversion between a byte array and a string
/* When a file stream is written, a conversion between a string and a byte array is often required.
Here is a brief description of this approach. */
1.string to byte[] array.
String msg = "HelloWorld";
Using UTF8 encoding
Byte[] bytes =system.text.encoding.utf8.getbyte (msg);
Using System default encoding
Byte[] bytes =system.text.encoding.default.getbyte (msg);
2.byte[] to String
String newmsg =system.text.encoding.utf8.getstring (bytes);
Coding issues
Why is Chinese garbled?
In UTF8 encoding, a Chinese character occupies two bytes.
In GBK encoding, a Chinese character occupies three bytes.
UTF8 encoding, save a Chinese character with two bytes, if you read it in GBK, read it in three-byte format. Of course it's garbled. The reverse is the same.
To sum up, whether it is 36 yards of shoes, wearing on the 50 yards of feet. Or 36 yards of feet, wearing 50 yards of shoes. It doesn't look very comfortable.
So, according to what format to write, in what format to read. is the positive solution.
Ps:1.utf8 is an international standard.
2.GB2312 is the national Standard Code, supports Chinese.
3.GBK is an extension to GB2312, which supports traditional Chinese.
What class can Dispose ()?
1.Dispose () indicates that the resource is freed. NET has a uniform convention or description for Dispose (). This Convention is represented as an interface.
Or this interface, is a red-headed, red-headed in the agreement on how to release resources.
All classes that implement the IDisposable interface can be freed and Dispose ();
So what classes in the class library implement the IDisposable interface?
My understanding is that it typically consumes only the classes or objects of memory resources in the managed heap. Dispose () is not normally required. The garbage collection is done.
However, for file handles, network port numbers, database connections, and so on, the CLR's garbage collection mechanism is no matter.
So this part of the content needs to implement IDisposable interface.
Exception handling for file stream operations
Only the FS is defined here and finally can be referenced.
FileStream FS =null;
Try
{
FS =new FileStream (@ "file path", FileMode.Create);
byte[] bytes = Encoding.Default.GetBytes ("HelloWorld");
Fs. Write (Bytes,0,byte. Length);
}
Finally
{
if (fs! = NULL)//If FS is not assigned a value, then direct Dispose throws a null pointer exception.
{
Fs. Dispose ();
}
}
simplifying The above wording, although rigorous but a little bit troublesome. Microsoft provides syntax sugars. is the using syntax using (a class that frees resources) {operation}//1. The operation is completed and will be released automatically. After the 2.using statement is compiled, the code similar to the above will be formed. is to use try finally.
StreamWriter and StreamReader
Write by line
StreamWriter SW =new StreamWriter (@ "target", true,encoding.getenconding ("GB2312"));
Sw. WriteLine ("HelloWorld");
Read by row
StreamReader SR =new StreamReader (@ "Source");
Sr. Readerline (); Returns one string at a time
. NET (go) of common class libraries