C # basic notes (Day 10 ),
1. Fields, attributes, methods, constructors
Field: Data Storage
Attribute: protection field, which limits the value and set value of the field
Method: describes the behavior of an object.
Constructor: Initialize an object (assign values to each attribute of the object in sequence)
Class member. If no access modifier is added, the default value is private.
Each private field is assigned a public attribute.
Attribute is essentially two methods
After the object is created
Assign a value to the property of this object using set
Run get when printing the value of this attribute.
This: the object of the current class
This: Call the current class
This separates attributes from local variables.
Constructor: 1. No return value, even void.
2. the constructor name is the same as the class name.
Constructors can be overloaded.
: This (name, 0, 0, gender)
New: 1. Open up a space in the memory
2. Create an object in the opened space
3. Call object constructor
Limitation: set get Constructor
Static Method class name. Method Name
Instance method object name. Method Name
Static methods can only access static members.
Objects cannot be created for static classes.
2. namespace
The namespace can be seen as a folder of classes.
Classes can be considered to belong to namespaces.
If there is no namespace for this class in the current project, you need to manually import
Namespace.
1) Click it with the mouse
2) alt + shift + F10
3) Remember the namespace and manually reference it.
3. reference the class of another project in one project
1) Right-click reference in Solution Explorer and add reference
2) reference a namespace
3. Value Type and reference type
Differences:
1. The value type and reference type are stored in memory differently.
2. The transfer method is different when the value type and the transfer reference type are passed.
The value type is referred to as value transfer, and the reference type is referred to as reference transfer.
The value type and reference type we learned:
Value Type: int, double, bool, char, decimal, struct, enum
Reference Type: string, custom class, array
Storage:
The value type is stored in the memory stack.
The reference type value is stored in the memory heap.
Heap, stack, and static storage areas
Int number = 10; create a space in the stack, store 10 in this space, and name this space number
String s = "123"; create a space in the heap, store "123" in this space, there is an address (reference) 0x001001,
Open up a space in the stack. The address 0x001001 In the heap is called s. S points to the memory in the heap.
Person zsPerson = new Person ();
ZsPerson. Name = "James ";
Create a space in the heap and store new Person (); "Zhang San" in this space. There is an address (reference)
Open up a space in the stack, store the address in the heap, and name it zsPerson.
4. String
1) Non-mutable strings
After you re-assign a value to a string, the old value is not destroyed, but a new space is created to store new values.
After the program ends, GC scans the entire memory. If it finds that some space is not pointed to, it will be destroyed immediately.
If the int value is re-assigned, the original value will be overwritten in the original stack space.
If the string value is re-assigned, a new value will be created in the original heap space. The storage address space in the stack remains unchanged.
Create string s1 = "zhangsan"
String s2 = "zhangsan"
Only one block of storage space is opened in the heap"
Create two spaces in the stack named s1 and s2 pointing to the space in the heap (address in the storage heap)
Window-instant-timely window-& s1 & s2 you can see that the memory addresses of s1 and s2 are the addresses in the stack, and the addresses in the stack are the addresses below.
2) We can regard the string as a read-only array of the char type.
ToCharArray (); converts a string to a char array
New string (char [] chs): converts a char array to a string.
1 string s = "abcdefg";2 char[] chs = s.ToCharArray();3 chs[0] = 'b';4 s= new string(chs);5 Console.WriteLine(s);6 Console.ReadKey();
Stopwatch Timer
Stopwatch sw = new Stopwatch ();
Sw. Start (); Start timing
Sw. Stop (); Stop timing
Sw. elapsed total running time measured by the current instance
StringBuilder sb = new StringBuilder ();
Sb. Append (I); Append
Can accumulate this I into sb
1 StringBuilder sb = new StringBuilder(); 2 //string str = null; 3 Stopwatch sw = new Stopwatch(); 4 sw.Start(); 5 for (int i = 0; i < 100000; i++) 6 { 7 //str += i; 8 sb.Append(i); 9 }10 sw.Stop();11 Console.WriteLine(sw.Elapsed);12 Console.ReadKey();
Why is string so slow, because it needs to open space every time
Stringbuilder is so fast because it has a space in the memory and is used in the same type.
Finally, stringbuild must convert tostring to string.
5. Various methods provided by strings
// Convert string to uppercase
LessonOne = LessonOne. ToUpper ();
// Convert the string to lowercase.
LessonOne = LessonOne. ToLower ();
// Compare the values of two strings
LessonOne. Equals (LessonTwo, StringComparison. OrdinalIgnoreCase)
Equals also StringComparison. OrdinalIgnoreCase enumeration. Ignore the case sensitivity of the string to be compared.
String s = "a B c 3 12-+ _, = fdf ";
// Split the string
// Write all unwanted characters in the char array
// Although the array is killed, an empty array is left ""
// Add StringSplitOptions. RemoveEmptyEntries.
Char [] chs = {'', '_', '=', '+ ',',','-'};
String [] str = s. Split (chs, StringSplitOptions. RemoveEmptyEntries );
Console. ReadKey ();
Exercise
Console. writeLine ("enter a date, for example,"); string s = Console. readLine (); // you do not need to create char [] chs. directly add it to string [] date = s. split (new char [] {'-'}, StringSplitOptions. removeEmptyEntries); Console. writeLine ("the date you entered is {0}-{1}-{2}-day", date [0], date [1], date [2]); Console. readKey ();
// Contains (included) to determine whether the string contains the specified string
// Replace (Replace) replaces a string with a new string, and returns
Exercise
1 string str = "national leader Lao Zhao"; 2 if (str. contains ("Old Zhao") 3 {4 str = str. replace ("Lao Zhao", "**"); 5} 6 Console. writeLine (str); 7 Console. readKey ();
1 // Substring capture string 2 string str = "today's weather is fine, good scenery everywhere"; 3 // use the string as an array, starting from subscript 0 to capture 4 str = str. substring (1); 5 // capture the string starting from the day, intercepting 2 Characters 6 str = str. substring (1, 2); 7 Console. writeLine (str); 8 Console. readKey ();
1 // StartsWith () determines whether the string starts with a substring value. 2 // EndsWith () determine whether to end with a substring value in the string. 3 // use the same 4 string str = "today's weather is fine, good scenery everywhere"; 5 if (str. startsWith ("today") 6 {7 Console. writeLine ("yes"); 8} 9 else10 {11 Console. writeLine ("not"); 12} 13 Console. readKey ();
1 // determine the subscript position of a string that appears for the first time in the string. If-1 is not returned, the int type accepts 2 string str = "good weather today, good scenery everywhere "; 3 int n = str. indexOf ('day'); 4 // Add an Int-type number to indicate the subscript of the nth 'day' in the string. 5 // int n = str. indexOf ('day', 2); 6 // if you want to find the subscript of all 'day', you need to use a loop to find 7 Console. writeLine (n); 8 Console. readKey ();
1 // LastIndexOf (): determines the last position of a string in the string. If no value is returned,-12 // LastIndexOf () is returned () we often use 3 string path = @ "c: \ a \ B \ c \ d \ e \ f \ g \ ff \ Cang \ ds \ fgd \ d \ old teacher .wav "; 4 // The text displayed after the last diagonal line is the most accurate, until the last 5 int index = path. lastIndexOf ("\"); two diagonal lines represent a diagonal line
Exercise
1 string path = @ "c: \ a \ B \ c \ d \ e \ f \ g \ ff \ Cang \ ds \ fgd \ d \ old master .wav "; @ indicates that \ In the string represents \ 2 int index = path. lastIndexOf ("\"); \ represents a \ 3 path = path in the string. substring (index + 1); The Truncation starts from \, so add 14 Console. writeLine (path); 5 Console. readKey ();
1 // Trim (): remove the leading and trailing spaces in the string. 2 // TrimEnd (): remove the trailing spaces in the string. 3 // TrimStart (): remove the leading space 4 string str = "hahaha"; 5 str = str. trim (); 6 Console. write (str); 7 Console. readKey ();
1 // string. isNullOrEmpty (): determines whether a string is null or null 2 string str = null; 3 if (string. isNullOrEmpty (str) 4 {5 Console. writeLine ("yes"); 6} 7 else 8 {9 Console. writeLine ("not"); 10} 11 Console. readKey ();
1 // string. Join (): Concatenates the array according to the specified string and returns a string. 2 string [] name = {"Zhang San", "Li Si", "Wang Wu", "Zhao Liu", "Tian Qi"}; 3 string str = string. join ("|", name); params variable parameter: You can put the array or parameter 4 Console. writeLine (str); 5 Console. readKey ();
1), Length: Get the number of characters in the current string
2) ToUpper (): converts a character to a large write form.
3) ToLower (): converts a string to lowercase.
4) Equals (lessonTwo, StringComparison. OrdinalIgnoreCase): Compares two strings, which can be case-insensitive.
5). Split (): splits the string and returns an array of the string type.
6) Substring (): truncates a string. The position to be intercepted is included in the screenshot.
7) IndexOf (): determines the position of a string that appears for the first time in the string. If-1 is not returned, the value type and reference type are stored differently in the memory.
8), LastIndexOf (): determines the position of the last occurrence of a string in the string. If not,-1 is returned.
9), StartsWith (): determines to start bool type judgment...
10), EndsWith (): Judge to end bool type judgment...
11), Replace (): Replace a string in the string into a new string
12) Contains (): determines whether a string Contains the specified bool type.
13), Trim (): Remove spaces before and after the string
14) TrimEnd (): removes spaces at the end of the string.
15) TrimStart (): removes the leading space in the string.
16), string. IsNullOrEmpty (): determines whether a string is null or
17), string. Join (): Concatenates the array according to the specified string and returns a string.
6. Review
Highlights of string
1) the string is unchangeable. Each new string will open up a new space in the memory.
2) string method
Difference between StringBuilder and String
A new instance is generated when String operations (such as value assignment and concatenation) are performed, while StringBuilder does not.
Use StringBuilder for operations, and convert ToString type to String type.
1 string path = @ "C: \ Users \ SJD \ Desktop \ 22.txt"; path 2 string [] str = File. readAllLines (path, Encoding. default); 3 // File (static class ). readAllLines (method, read all rows) read all garbled characters 4 // Encoding. remove garbled characters by Default 5 Console. readKey ();
7. Exercise
Convert char array to string type
1 char[]chs={‘1’,‘2’,‘3’};2 string str=new string(chs);
Returns the position of all e in the string.
@ Method 1 (required)
1 string str = "daghdewejhadgwehhjfhajejwwe"; 2 int index = str. indexOf ('E'); 3 Console. writeLine ("1st e occurs at {0}", index); 4 int count = 1; 5 while (index! =-1) 6 {7 index = str. indexOf ('E', index + 1); 8 count + = 1; 9 if (index =-1) 10 {11 break; 12} 13 Console. writeLine ("number {0} e appears at {1}", count, index); 14} 15 Console. readKey ();
Method 2
Search for multiple words.
1 string str = "daghdewejhadgwehhjfhajejwwe";2 for (int i = 0; i < str.Length; i++)3 {4 if(str[i]=='e')5 {6 Console.WriteLine(i);7 }8 }9 Console.ReadKey();
8. Inheritance
Each class must be written in a class file.
We may write duplicate members in some classes. We can put these duplicate members,
Encapsulate them into a class as the parent class of these classes.
Format subclass: parent class
Student, Teacher, Driver subclass derived class
Person parent class base class
If a subclass inherits the parent class, what does the subclass inherit from the parent class?
First, the subclass inherits the attributes and methods of the parent class, but the subclass does not inherit the private fields of the parent class. And cannot be seen.
One of Li's wealthy relatives hangs up. The beneficiary is Li, but he does not have a bank password. He can't use it.
Q: Does the subclass inherit the constructor of the parent class?
A: The subclass does not inherit the constructor of the parent class,. Sub-classes call constructors without parameters in the parent class by default,
Create a parent class object so that child classes can use members in the parent class.
Therefore, if a new constructor with parameters is rewritten in the parent class, the parameter-free constructor will be killed,
The subclass cannot be called, so the subclass reports an error.
After the parent class has been executed, no parameter constructor is executed, and then the sub-class
Executing the constructor of the parent class is equivalent to creating an object of the parent class.
Because there is no parent class object, the subclass cannot use the attributes of the parent class.
When a subclass object is created, the parent class object is also created, so that attributes and methods of the parent class and members of the parent class can be used.
The subclass contains its own attributes and parent class objects (constructors). The internal parent class also contains its attributes and methods.
The process of inheriting the constructor can be added to the attributes of the subclass.
The parent class calls without parameters by default, instead of parameters.
Solution:
1) re-write a non-parameter constructor in the parent class.
2) Call the constructor of the parent class displayed in the subclass, using the Keyword: base ()
9. inherited features
1. Inheritance: a subclass can only have one parent class.
2. Inheritance: Grandpa-Dad-son-grandson
10. view the class diagram
Right-click the class file-View-view the class diagram to view the inheritance relationship between classes.
11. object is the base class of all classes.
If a class is not inherited from another class, the class inherits from the object
12. new Keyword
1) create an object
2) Hide members of the same name inherited from the parent class.
The hidden consequence is that the Child class cannot call the members of the parent class.
If the name of the subclass member is the same as that of the parent class member, the inherited parent class member is hidden.
No error is reported after new is added.
13. Review
Value Type
Reference Type
String immutable
Yituo Method
StringBuilder
Inheritance
Transmission
Relationship between subclass and parent class Constructor
What does the subclass inherit from the parent class?
New Keyword