Due to a recent requirement in the project, string splitting is required, and then the split elements are added to a listview control one by one. The Code is as follows:
Namespace initaltest {class program {static void main (string [] ARGs) {string S = "1 + 2 + 3 + 4 + 5 + 6"; // Question 1: the first parameter of the split method is a string [] object. Why do some methods do not use the new operator when the parameter is string? String [] sarrs = S. split (New String [] {"+"}, stringsplitoptions. removeemptyentries); // Question 2: when traversing an array or set, should I choose foreach or? Foreach (string Sarr in sarrs) {console. writeline (Sarr);} console. readkey (); // program output result:/* 1 2 3 4 5 6 */}}}
Question 1: Why do some methods not use the new operator when the parameter is a string object?
In principle, CLR requires that all objects be created using the new operator. For example, myclass MC = new myclass (); int I = new int (); but some types are frequently used. Therefore, the compiler allows code to operate on them with simplified syntax, for example: int I = new int (); can be abbreviated as: int I = 0; this syntax not only enhances the readability of the Code, the generated il code is exactly the same as the Il code generated when the new operator is used. The compiler calls this directly supported type a primitive type. String is a primitive type, so you can use the shorthand syntax when creating a String object.
Question 2: Do I use for or foreach when traversing an array or set?
This mainly depends on the difference between for and foreach.
In common: For and foreach can be used to traverse arrays and collections.
Differences: 1. syntax. Foreach is more concise than.
2. Semantics. Foreach is easier to understand than.
3. Performance. Foreach has higher performance than.
Therefore, when traversing an array or set, it is best to use the foreach statement. As long as the object implements the ieumerable interface.