C # basic notes (13th days ),

Source: Internet
Author: User
Tags acer

C # basic notes (13th days ),

1. Review
Generic set
List <T>
Dictionary <Tkey, Tvalue>
Packing and unpacking
Packing: Convert the value type to the reference type
Binning: converts a reference type to a value type.
We should try to avoid packing or unpacking in the code.
File stream
FileStream StreamReader and StreamWriter
Polymorphism: Virtual Methods, abstract classes, and interfaces
Virtual method:
Abstract class:

Set: space name Collections. Generic
List <int> list = new List <int> ();
The difference between ArrayList and ArrayList: the element type is determined, and no packing or unpacking is generated when the set is used.
Dictionary <int, string> dic = new Dictionary <int, string> (); set of key-value pairs
Dic. Add (1, "Zhang San"); An exception is thrown when the same key is added.
Dic [2] = "Li Si" adding the same key will overwrite the original key value in this way
Set key-value pairs using foreach Loop
Foreach (var item in collection)
{

}
Foreach (KeyValuePair <int, string> kv in dic)
{
Console. writeline ("{0} ------ {1}", kv. key, kv. value );
}
Console. readkey ();

File stream
File FileStream operation byte StreamReader StreamWriter Operation character
It is best to put the text and data in the relative path (in debug)
The Code should be written in using (), because its resources will not be automatically released, and we must manually release them. Writing them in using can help us automatically Recycle resources.
Using (FileStream fsRead = new FileStream ("zucema.txt", FileMode. OpenOrCreate, FileAccess. Read ))
{
Byte [] buffer = new byte [1024*1024*5];
// The actual number of bytes read this time
Int r = fsRead. Read (buffer, 0, buffer. Length );
// Parse each element in the byte array into a string according to our encoding format
String s = Encoding. Default. GetString (buffer, 0, r );
Console. WriteLine (s );
}
Console. ReadKey ();
If it is big data, it must be read cyclically.

Write
Using (FileStream fsWrite = new FileStream (@ "C: \ Users \ SJD \ Desktop \ new.txt", FileMode. OpenOrCreate, FileAccess. Write ))
{
String s = "ABC ";
Byte [] buffer = Encoding. UTF8.GetBytes (s );
FsWrite. Write (buffer, 0, buffer. Length );
}
Console. WriteLine ("successfully written ");
Console. ReadKey ();
Overwrite by byte
To Append the file, change FileMode. OpenOrCreate to FileMode. Append.

Polymorphism
Show multiple States and types to an object
Benefits of write Polymorphism
1. Reduce code
2. Shielding the differences between sub-classes and writing common code, applicable to the code of each sub-class

Virtual Methods and abstract classes

Declare the parent class to specify the subclass object
Typical examples of Virtual Methods: the wooden duck will be called, the rubber duck will be called, and the real duck will be called, but they are called in different ways. The real duck is a parent class and makes sense and needs to be instantiated.
Abstract classes are usually used later.

2. access modifier in C #
Public: public
Private: private. It can only be accessed within the current class.
Protected: protected, accessible only within the current class and its subclass
Internal: It can only be accessed in the current project. In the same project, internal and public have the same permissions.
In the same project, Internal has a higher permission than protected. However, once a project is crossed, the protected permission must be greater than internal.
Protected internal: protected + internal permission

1) there are only two access modifiers for the modifier class: public internal
By default, the class without the Public modifier is replaced by Internal.

2) The accessibility is inconsistent.
The access permission of the subclass cannot be higher than that of the parent class, and the members of the parent class are exposed.
Because of the inheritance passed, the Child class can use the members of the parent class, but the write permission of the parent class is low to avoid being accessed to members by other projects.

3. Design Mode
Design is a way for this project
23 design modes
The design pattern helps us solve problems in daily development.

4. Simple Factory Design Model

5. Value Type and reference type
Value Type: int, double, char, decimal, bool, enum, struct storage Stack
Reference Type: string, array, custom class, set, object, interface heap

Value Transfer and reference Transfer
When copying a value type, the value itself is passed.
When copying a reference type, the reference of the heap object is passed.

6. serialization and deserialization
Serialization: converts an object to binary.
Deserialization: converts binary data to an object.
Purpose: transmit data.
Only binary data can be transmitted over the network.
Serialization:
1) mark this class as serializable.
Mark a [Serializable] above the class. Only objects marked by the class can be serialized.

Example: serialization
// Transfer the object p to the peer computer
Person p = new Person ();
P. Name = "James ";
P. Age = 19;
P. Gender = 'male ';
Using (FileStream fsWrite = new FileStream (@ "C: \ Users \ SJD \ Desktop \ p.txt", FileMode. OpenOrCreate, FileAccess. Write ))
{
// Serialize the object
BinaryFormatter bf = new BinaryFormatter ();
Bf. Serialize (fsWrite, p );
}
Console. WriteLine ("serialization successful ");
Console. ReadKey ();

Deserialization
// Receives binary deserialization from the recipient into an object
Person p;
Using (FileStream fsRead = new FileStream (@ "C: \ Users \ SJD \ Desktop \ p.txt", FileMode. Open, FileAccess. Read ))
{
BinaryFormatter bf = new BinaryFormatter ();
// Forcibly convert an object to a person
P = (Person) bf. Deserialize (fsRead );
}
Console. WriteLine (p. Name );
Console. WriteLine (p. Age );
Console. WriteLine (p. Gender );
Console. ReadKey ();

7. partial Classification
Three people work together on a project, and each person needs to develop a person class. If you cannot write it, I cannot write it.
Add a partial before each class to indicate a partial classification.
Public partial class Person
{
}
Public partial class Person
{
}
Indicates that these two classes form the person class and can be written at the same time.
There is also a benefit that both public and private data can be read from each other.
The same method cannot be used in a partial category, but it can be overloaded. A considerable class is written in different places.

8. sealed sealing class
Sealed is used to mark a class as a seal class.
Public sealed class Person
Feature: The sealed class cannot be inherited by other classes, but can be inherited from other classes.

9. Override the ToString method.
Person p = new Person ();
Console. writeline (p. tostring ());
Console. readkey ();
The printer will display the namespace of this object.

* *** Why can all types be ToString?
Because all types of parent classes are objects
Some methods provided in the object can be called by subclass
Tostring can be called
ToString is the virtual method of the object.
Therefore, all the variables of all objects can call ToString.

10. Interface
The inherited feature is a single property. Only one parent class is allowed for a subclass.
A subclass can be written as an interface to inherit two parent classes.
The keyword for declaring an interface is interface.
In English, the start and end of "I" can indicate the ability

An interface is a specification and capability.
Only by complying with this specification can we survive
Capability: a certain function can be used.

Interface syntax and features
Format:
[Public] interface I... able
{
Member;
}

Public interface IFlayable
{
Void Fly ();
String Test ();
}
1. return values can be returned, and strings can be used.
2. Access modifiers cannot be added to the interface members. The default value is Public.
3. Interface members cannot be defined and function with method bodies cannot be written.
4. Data (fields) cannot be stored on interfaces, and data is stored using classes.
5. You can write a method without a method body (automatic attribute)
6. Methods and automatic attributes

Why is automatic attribute
Although we do not write fields, a private field is automatically generated during compilation.
Only constructors are allowed.
Public int Age
{
Get;
Set;
}

Automatic attributes are essentially two functions. One is get and the other is set.

Methods and attributes are usually put in interfaces (essentially only methods)

The access modifier is not added to the interface. The default value is public.
Class. The default value is private.
Example:
No matter what manufacturer you are. The USB interface must be made at last. You can insert the mouse and keyboard. All must comply with USB specifications. All manufacturers must follow the specifications. There are also special features, such as Apple, with no network cable ports. Mobile phones are also moving towards a standard.
* ** When will the interface be used?
1. When classes need to be inherited

* *** An interface is a standard.
As long as a class inherits an interface, this class must implement all the members of this interface.

For polymorphism.
The interface cannot be instantiated.
That is to say, the interface cannot be new (the object cannot be created)

 

 

The "access modifier" cannot be added to the interface members. The access modifier of the interface members is public and cannot be modified.


(Public by default)
The members in the interface cannot have any implementation ("do not do it", but defines a group of unimplemented members, just like the abstract class, just inherit their subclass ).

 

Interfaces can only contain methods, attributes, indexers, and events, and cannot contain "fields" and constructors.

Interfaces and interfaces can be inherited.

An interface cannot inherit a class, but a class can inherit interfaces (an interface can only inherit interfaces, and a class can inherit both interfaces and classes)


The subclass that implements the interface must implement all the members of the interface.


A class can inherit A class and implement multiple interfaces at the same time. If A subclass inherits the parent class A and implements the interface IA, A must be written before IA in syntax.


Class MyClass: A, IA {}, because the class is single-inherited.


Display implementation interface purpose: Solve the Problem of duplicate names of methods
When to display the de-implementation interface:
When the methods and parameters in the inherited interface are the same, use the displayed Interface

 

When an abstract class implements an interface, a subclass is required to implement the interface.


Object-oriented (Interface) Programming

11. display implementation Interface
The display implementation interface is used to solve the problem of duplicate names.

Example:
Public class Bird: IFlyable
{
Public void Fly ()
{
Console. WriteLine ("Birds fly ");
}
Void IFlyable. Fly ()
{
Console. WriteLine ("I am the flying interface ");
}
}

IFlyable fly = new Bird ();
Fly. Fly (); // The Fly of the interface is called.

Bird bird = new Bird ();
Bird. Fly (); // you can call your own Fly.

12. Summary
// When can I use the virtual method to implement polymorphism?
// When can I use abstract classes for polymorphism?
// When can I use interfaces to implement polymorphism?

Among the several classes that I provide to you, if you can abstract a parent class, and this parent class must write the methods that these sub-classes share, then you don't know how to write this method, so you can use abstract classes to write this polymorphism.
Instead, the abstract parent class can be written as a method, and I want to create an object for this parent class, I will use the virtual method.
The parent classes cannot be found in these classes, but they all share a common behavior and capability. At this time, the interface is used to realize polymorphism (analogy: birds and airplanes have no parent classes, but they can fly, so they cannot write a parent class for them to inherit)

Real ducks can swim, wooden ducks can not swim, rubber ducks can swim
There is no way to extract a parent class to swim, because the wooden duck can not swim, there is no way to use the virtual Method
There is no way to write the abstract method, because the real duck needs to be created, and the real duck makes sense.
Therefore, the interface is the most suitable


13. Supermarket Cash Register System
Guid can generate a unique ID in the world. // Do not repeat
Guid. NewGuid () can be ToString ()


// Use the parent class as a collection to shield the differences, but it is hard to find them. All the goods are mixed together.
// List <ProductFather> list = new List <ProductFather> ();
// Store goods and collections (because goods will be added)
// List <sumeda> listSum = new List <sumeda> ();
// List <Acer> listAcer = new List <Acer> ();
// List <JiangYou> listJiangYou = new List <JiangYou> ();
// List <Banana> listBanana = new List <Banana> ();
List <ProductFather> list = new List <ProductFather> ();
I put another set in a set.
The content in list <> should be the type of this set.
List <ProductFather> list2 = new List <ProductFather> ();
Differences:
When adding data to list2, you can directly add the goods objects, such as Samsung, mobile phones, laptops, soy sauce, to the collection.
The disadvantage is that it is difficult to obtain data. If the subscript is saved, you have to debug it. It is very troublesome to see which object the data corresponding to this subscript is.

So what do we mean by using two sets and two sets?
When adding data to a list
List. Add () to Add a set. In fact, this collection is the shelf
Adding data to him is not a commodity, but a shelf
Both list and List2 represent the entire repository.

Adding a warehouse with list2 is to take the data back and directly throw it into the warehouse.
List is to add an array of the collection, add a set of data to the warehouse, and the warehouse goods are concentrated to the shelf
A shelf is a collection of goods (shelves are all placed in the goods), add shelves, there are four shelves, so add four elements in.

List <parent class> list = new List <parent class> ();
List [0] = shelves
What type of product parent class can be put in the past
To add goods to a warehouse, we actually add goods to list [0], list [1], list [2]...
In this way, you can directly obtain the shelf where the goods are located.

In the warehouse, besides commodities and shelves
Only the Warehouse is created and there is no shelf

When to create a shelf?
Add a shelf to the warehouse when creating a CangKu object

Example:
// Use the parent class as a collection to shield the differences, but it is hard to find them. All the goods are mixed together.
// List <ProductFather> list = new List <ProductFather> ();
// Store goods and collections (because goods will be added)
// List <sumeda> listSum = new List <sumeda> ();
// List <Acer> listAcer = new List <Acer> ();
// List <JiangYou> listJiangYou = new List <JiangYou> ();
// List <Banana> listBanana = new List <Banana> ();
List <ProductFather> list = new List <ProductFather> ();
// List [0] storage Acer computer
// List [1] Stores SamSung mobile phones
// List [2] store soy sauce
// List [3] banana Storage
/// <Summary>
/// Add a shelf to the warehouse when creating an object in the warehouse
/// </Summary>
Public CangKu ()
{
// List. Add (new List <ProductFather> ());
// List. Add (new List <ProductFather> ());
// List. Add (new List <ProductFather> ());
// List. Add (new List <ProductFather> ());
// Use the parent class to shield the Differences Between Shelves
// For Loop is used when there are many shelves
For (int I = 0; I <4; I ++)
{
List. Add (new List <ProductFather> ());
}
}
/// <Summary>
/// Purchase
/// </Summary>
/// <Param name = "strType"> goods type </param>
/// <Param name = "count"> quantity of goods </param>
Public void GetPros (string strType, int count)
{
// There are a lot of goods that can't be added at a time, and can be added through the for Loop
For (int I = 0; I <count; I ++)
{
// There are four possible strType cargo types, so we can make a Multi-condition judgment on it.
Switch (strType)
{
Case "Acer": list [0]. Add (new Acer (Guid. NewGuid (). ToString (), 1000, "Acer Notebook "));
Break;
Case "sumguid": list [1]. Add (new SumSung (Guid. NewGuid (). ToString (), 2000, "Stick phone "));
Break;
Case "JiangYou": list [2]. Add (new JiangYou (Guid. NewGuid (). ToString (), 10, "Soy Sauce "));
Break;
Case "Banana": list [3]. Add (new Banana (Guid. NewGuid (). ToString (), 50, "big Banana "));
Break;
}


}


How to extract goods
/// <Summary>
/// Extract the goods from the warehouse
/// </Summary>
/// <Param name = "strType"> </param>
/// <Param name = "count"> </param>
/// <Returns> </returns>
// Returns a parent class set or Array
Public ProductFather [] QuPros (string strType, int count)
{
// Put the goods in the array to return
ProductFather [] pros = new ProductFather [count];
// The incoming goods are placed one by one, and the receiving goods are also retrieved one by one.
For (int I = 0; I <count; I ++)
{
Switch (strType)
{
// The first [0] On the shelf. After the first one is taken away, the second one is taken to the top to become the first one [0].
// This is only a value assignment operation, and the number on the shelf has not changed
// List [0] is the shelf of the Acer notebook, and list [0] [0] is the first notebook on the shelf, which is put in the pros array after it is obtained
Case "Acer ":
// Determine whether the shelf is empty
If (list [0]. Count = 0)
{
Break;
}
Pros [I] = list [0] [0];
// Remove the first one and delete one
List [0]. RemoveAt (0 );
Break;
Case "sumeda ":
If (list [1]. Count = 0)
{
Break;
}
Pros [I] = list [1] [0];
List [1]. RemoveAt (0 );
Break;
Case "JiangYou ":
If (list [2]. Count = 0)
{
Break;
}
Pros [I] = list [2] [0];
List [2]. RemoveAt (0 );
Break;
Case "Banana ":
If (list [3]. Count = 0)
{
Break;
}
Pros [I] = list [3] [0];
List [3]. RemoveAt (0 );
Break;
}
// Return the set

}
Return pros;
}

You also need a method to display the goods.


13. Summary
Pass value and reference pass Value Pass pass the value itself
References pass references to objects.
Ref: change the value transfer to reference transfer (not necessarily true)
Interface syntax features
Display implementation Interface
When do I use interfaces?
Partial Classification)
Sealed)
Serialization and deserialization objective: to transmit data
Simple Factory Design Model
5 Access Modifiers

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.