C # basic notes (12th days ),

Source: Internet
Author: User

C # basic notes (12th days ),

1. Review
Rys conversion:
1) subclass can be assigned to the parent class (if a method requires a parent class as a parameter, we can pass the first subclass object)
2) If the parent class contains a subclass object, you can convert the parent class into a subclass object.

Is and as determine whether the conversion is successful

1 Person p = new Student (); 2 // if (p is Student) 3 // {4 // (Student) p ). studentSayHello (); 5 //} 6 // else 7 // {8 // Console. writeLine ("Conversion failed"); 9 //} 10 Student ss = p as Student; 11 ss. studentSayHello (); 12 Console. readKey ();
View Code

In a key-value pair, the key must be unique.
View the data in the key-value pair set in a foreach loop, and deduce the value based on the key

Path can obtain the file name, directory, Path, etc.
Both Path and File are static classes.

ReadAllBytes () read data Encoding. Default. GetString (byte array)
Byte [] buffer = File. ReadAllBytes (@ "C: \ Users \ SJD \ Desktop \ 123.txt ");
// Each element in the byte array must be decoded into a string according to the encoding format we specify.
// UTF-8 GB2312 gbk askii Unicode
// UTF8, UTF7, and UTF32 are encoded in Unicode format.
// GB2312 Simplified Chinese, GBK both simplified and traditional
// Encoding. Default the format in which the Default DNS is stored is used.
String s = Encoding. GetEncoding ("GB2312"). GetString (buffer );
Console. WriteLine (s );
Console. ReadKey ();

WriteAllBytes () write data Encoding. Default. GetBytes (string)
String str = "study every day ";
Byte [] buffer = Encoding. Default. GetBytes (str );
File. WriteAllBytes (@ "C: \ Users \ SJD \ Desktop \ new.txt", buffer );
Console. WriteLine ("successfully written ");
Console. ReadKey ();

ReadAllLines () reads data in rows and returns an array of the string type.
String [] contents = File. ReadAllLines (@ "C: \ Users \ SJD \ Desktop \ 123.txt", Encoding. Default );
Foreach (string item in contents)
{
Console. WriteLine (item );
}
Console. ReadKey ();

ReadAllText () reads data in the form of TEXT, returns a string type string
String str = File. ReadAllText (@ "C: \ Users \ SJD \ Desktop \ 123.txt", Encoding. Default );
Console. WriteLine (str );
Console. ReadKey ();

WriteAllLines () write data to overwrite the data with a string array
File. WriteAllLines (@ "C: \ Users \ SJD \ Desktop \ new.txt", new string [] {"Zhang San", "Li Si", "Wang Er Ma Zi "});
Console. WriteLine ("successfully written ");
Console. ReadKey ();

WriteAllText () write data to overwrite data with string-type strings
File. WriteAllText (@ "C: \ Users \ SJD \ Desktop \ new.txt", "Zhang sanli siwang Erma zi ");
Console. WriteLine ("successfully written ");
Console. ReadKey ();

AppendAllLines (), AppendAllText (), and AppendText () are all appended writes without overwriting.

The biggest drawback of the File class is that it can only be used to read small files.
It is a waste of memory because it reads all the data at once.
File streams are required to read large files.
ReadAllText () and ReadAllLines () are used for reading text, and ReadAllBytes () is used for reading multimedia files ()
The returned array can accurately manipulate the data of each row. The returned string can only return one whole.

2. absolute and relative paths
Absolute path: the file can be directly found on my computer through the given path.
Relative Path: the path of the file to the application. Stored in the same directory of the execution file. You do not need to specify a path during running.

It is best to use relative paths when writing code, because absolute paths can only be used on my own computer. The relative path can be used on any computer.
Use relative paths as much as possible during development.

3. List generic set
Benefits of ArrayList: 1) the length of the set can be changed at will
2) There is no requirement for the data type to be added.
What type of data declaration should be included?
// Create a generic set
List <int> list = new list <int> (); you do not need to manually reference the namespace.
List generic sets have the advantages of ArrayList, and the length of the set can be changed at will. You do not need to perform strong conversion during reading.
// List generic sets can be converted to Arrays
List set to array
Int [] nums = List. ToArray ();
// Create a string-type generic set
List <string> listStr = new List <string> ();
// Convert a string-type generic set to an array of the string type
String [] list = listStr. ToArray ();
// Converts an array of the string type to a string-type generic set.
List <string> listStrTwo = list. ToList <string> ();

The ArrayList set and HashTable are rarely used. It is not convenient.

4. packing and unpacking
Packing: converts the value type to the reference type.
Binning: converts a reference type to a value type.
Int n = 10;
Object o = n; // boxed
Int nn = (int) o; // unpack
Packing will be slower (10 times worse) than normal, and try to avoid packing and unpacking in the code.
// This location does not contain any type of packing or unpacking
String str = "123 ";
Int n = convert. toint32 (str );

Check whether the two types are packed or unpacked, and whether there is an inheritance relationship between the two types.
If there is an inheritance relationship, packing or unpacking may occur. If there is no inheritance relationship, they will not be packed or unpacked.
Example:
Int n = 10;
IComparable I = n; // The boxed IComparable is also a reference type and has an inheritance relationship.

5. Dictionary
Basically the same as BashTable
You can use key-value pairs to read data.
Example:
Dictionary <int, string> dic = new Dictionary <int, string> ();
Dic. Add (1, "Zhang San ");
Dic. Add (2, "Li Si ");
Dic. Add (3, "Wang Erma zi ");
Dic [1] = "new ";
Foreach (KeyValuePair <int, string> kv in dic)
{
Console. WriteLine ("{0} ------ {1}", kv. Key, kv. Value );
}

6. FileStream file stream
What is the difference between reading and File?
Two Cylinders, an empty cylinder, and B filled with water. Install B's water in.
File is used to pull B up and directly pour water into. However, it will put a lot of pressure on the users, and small people cannot resist this water.
FileStream is used to scoop B's water to. 1 scoop each time

File Read all of the files at once.
FileStream is read at (there is basically no pressure on the memory)

// FileStream can operate on any types of files in bytes.
// For StreamReader and StreamWriter, only text files can be operated.
The advantage of these two types of files is that they can operate large files with less pressure.
If you use a small File, the File class will be OK. Hundreds of K

* ***** Learning. net is to learn how to use these classes. The more you will be, the more you will be.
FileStream fsRead = new FileStream (@ "C: \ Users \ SJD \ Desktop \ 123.txt", FileMode. OpenOrCreate, FileAccess. Read );
// FileStream fsRead = new FileStream (1. path of the file to be operated, 2. what operations do you want to perform on the file? 3. what operations do you want to perform on the data in this file .);
Enumeration
Read after opening
Byte [] buffer = new byte [1024*1024*5]; // The limit byte array can only be set to 5 MB
// FsRead. Read (1. Limited byte, 2. indicates where data is written, 3. Maximum number of bytes Read );
Int r = fsRead. Read (buffer, 0, buffer. Length );
// Int type returned
// Only 3.8 M, but the r returned by each read of 5 M is the actual number of valid bytes for this read.
// The data is in the byte array and cannot be understood. Therefore, each element in the byte array must be decoded into a string according to the encoding format I specified.
// Decodes each element of the byte array into a string according to the specified encoding format
String s = Encoding. Default. GetString (buffer );
// Close the stream when it is used up
FsRead. Close ();
// Release the resources occupied by the stream
FsRead. Dispose ();
GC cannot recycle file streams
Console. WriteLine (s );
Console. ReadKey ();
// The number of valid bytes is small, and most of the printed values are empty.
// If the number of bytes is exceeded, no decoding is performed.
String s = Encoding. Default. GetString (buffer, 0, r); // start decoding from 0 and decode r.
// The decoded value is the number of valid r bytes, but the actual read value is 5 MB.

// If the size of big data exceeds 5 MB, it must be read cyclically.

// Use FileStream to write data

7. Write the process of creating a file stream object in using, which will automatically help us release the resources occupied by the stream.
Syntax provided by Microsoft, you do not need to write fsRead. Close (); and fsRead. Dispose ();
Using ()
{

}
The process of creating an object is written in (), and reading and writing are written in {}.
Using (FileStream fsWrite = new FileStream (@ "C: \ Users \ SJD \ Desktop \ new.txt", FileMode. OpenOrCreate, FileAccess. Write ))
{
String str = "check if I overwrite you ";
Byte [] buffer = Encoding. Default. GetBytes (str );
FsWrite. Write (buffer, 0, buffer. Length );
}
Console. WriteLine ("Write OK ");
Console. ReadKey ();

UTF-8 is used for writing and reading without garbled characters.
Encoding. UTF8.GetBytes (str );

8. Multi-media copy of FileStream
Static void Main (string [] args)
{
// Train of thought: Read the multimedia file to be copied first, and then write it to your specified location.
String source = @ "C: \ Users \ SJD \ Desktop \ see.mp4 ";
String target = @ "C: \ Users \ SJD \ Desktop \ new.mp4 ";
CopyFile (source, target );
Console. WriteLine ("Copy OK ");
Console. ReadKey ();
}

Public static void CopyFile (string source, string target)
{
// 1. Create a stream for reading.
Using (FileStream fsRead = new FileStream (source, FileMode. Open, FileAccess. Read ))
{
// Create a stream for writing
Using (FileStream fsWrite = new FileStream (target, FileMode. OpenOrCreate, FileAccess. Write ))
{
Byte [] buffer = new byte [1024*1024*5];
// Because the file may be large, we should read it through a loop during reading.
While (true)
{
// Returns the actual number of bytes read this time.
Int r = fsRead. Read (buffer, 0, buffer. Length );
// If 0 is returned, nothing is read.
If (r = 0)
{
Break;
}
FsWrite. Write (buffer, 0, r );
}
}
}
}

9. StreamReader and StreamWriter
FileStream is an operation byte (required)
StreamReader and StreamWriter are operation Characters
// When StreamWriter is used to write a text file, true is append write, Not Overwrite
Using (StreamWriter sw = new StreamWriter (@ "C: \ Users \ SJD \ Desktop \ new.txt", true ))
{
Sw. Write ("check if I overwrite you ");
}
Console. WriteLine ("Write OK ");
Console. ReadKey ();

10. Polymorphism
// Concept: enables an object to show multiple States (types)
Example:
Chinese cn1 = new Chinese ("Han Mei ");
Chinese cn2 = new Chinese ("Li Lei ");
Japanese j1 = new Japanese (" ");
Japan ese j2 = new japan ese ("Well edge ");
Korea k1 = new Korea ("Jin xiuxian ");
Korea k2 = new Korea ("Jin xianxiu ");
American a1 = new American ("Kobe Bryant ");
American a2 = new American ("o'neill ");
Person [] pers = {cn1, cn2, j1, j2, k1, k2, a1, a2 };
For (int I = 0; I <pers. Length; I ++)
{
If (pers [I] is Chinese)
{
(Chinese) pers [I]). SayHello ();
}
Else if (pers [I] is Japanese)
{
(Japan) pers [I]). SayHello ();
}
Else if (pers [I] is Korea)
{
(Korea) pers [I]). SayHello ();
}
Else
{
(American) pers [I]). SayHello ();
}
}
Console. ReadKey ();

Pers [I]. SayHello () is only used to read the corresponding methods under each subclass.

// Three methods for implementing polymorphism: 1. Virtual method 2. abstract class 3. Interface

11. methods to achieve Polymorphism
1) Virtual Methods
Steps:
1. Mark the method of the parent class as a virtual method and use the keyword virtual. This function can be rewritten by the quilt class.
Add a virtual
In this way, the parent function is marked as a virtual method.
Add override to override the method with the same name as the subclass.

The object of the parent class is still called, but this method is re-called, so the subclass method is called.
The method of calling the object
Allows an object to express multiple types and write common code. Remove one of their differences with the greatest benefit
The advantage of polymorphism is that it reduces a lot of code and enhances the maintainability.

To use the virtual method, you must first use the keyword virtual for a parent class.
Use the keyword override For the subclass

2) abstract class
When the methods in the parent class do not know how to implement them, you can consider writing the parent class as an abstract class and the method as an abstract method.
Use abstract to mark parent classes and Methods
Example:
Public abstract class animal
{
Public abstract void call ();

}
Meaning: rewrite the subclass
The abstract method must have no method body and must be marked with abstract
Because I don't know how to implement this method, I just don't implement it. The abstract class has no method body.
Public void Test ()
{
// Empty implement method body
}

Abstract classes cannot create objects, and interfaces cannot create objects.

1. abstract members must be marked as abstract members and cannot be implemented in any way.
2. Abstract members must be in abstract classes.
3. abstract classes cannot be instantiated.
4. After the subclass inherits the abstract class, all abstract members in the parent class must be overwritten.
(Unless the subclass is also an abstract class, you can not override it)
5. The access modifier of the abstract member cannot be private.
6. the abstract class can contain instance members.
In addition, the instance members of the abstract class can be implemented without the quilt class.
7. abstract classes have constructors, although they cannot be instantiated.
8. If the abstract method of the parent class contains parameters. The subclass that inherits this abstract parent class must input the corresponding parameters when rewriting the parent class method.
If there is a return value in the abstract method of the abstract parent class, the subclass must also input the return value when rewriting this abstract method.

==================
If the methods in the parent class are implemented by default and the parent class needs to be instantiated, you can define the parent class as a common class and implement polymorphism using the virtual method.
If the methods in the parent class are not implemented by default and the parent class does not need to be instantiated, the class can be defined as an abstract class.

In the parent class
Public abstract void Bark (); abstract class

Public abstract string Name abstract attribute
{
Get;
Set;
}

An error is reported during the test.
To inherit, locate the subclass, and place the cursor behind the inheritance class. The attributes of the shift + alt + f10 (implement the abstract class) subclass method will be overwritten.

If a subclass inherits an abstract parent class, this subclass must implement all abstract members in this abstract parent class.
Abstract classes can write non-Abstract members.
The parent class cannot create objects by itself, but can be used in subclass inheritance.
Therefore, the parent class can have abstract members or non-Abstract members.
You cannot write an abstract member in a non-abstract class.

The return value and parameters are the signatures in the method.

// Use polymorphism to calculate the area and perimeter of the rectangle and the area and perimeter of the circle
// Shap shape = new Circle (5 );
Shap shape = new Square (5, 6 );
Double area = shape. GetArea ();
Double perimeter = shape. GetPerimeter ();
Console. WriteLine ("the area of this shape is {0}, and the circumference is {1}", area, perimeter );
Console. ReadKey ();

12. Summary
List <T>
Dictionary <Tkey, Tvalue>
The advantage of ArrayList is that there is no disassembly box

FileStream operation byte
SteamReader and StreamWriter
Large files can be operated

Flie can only operate on small files

Disassembling box
Packing is from value type to reference type
Binning is from reference type to Value Type
Unpacking affects the system performance and takes time to run. Try to avoid box Disassembly

Polymorphism
The virtual method has an implementation of the parent class, and the parent class needs to create an object using the virtual method.
The abstract class parent class is not implemented. The parent class does not need to create objects with abstract classes.
Abstract classes need to master the characteristics
Interface

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.