C # Basic notes (13th day)

Source: Internet
Author: User

1. Review
Generic collection
List<t>
Dictionary<tkey,tvalue>
Packing and unpacking
Boxing: Converting a value type to a reference type
Unpacking: Converting 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 method, abstract class, interface
Virtual method:
Abstract class:

Collection: Space name Collections.generic
List<int> list=new list<int> ();
The difference between the ArrayList and the set: Determines the type of the element and does not release boxing and unpacking when using the collection
Dictionary<int,string> dic=new dictionary<int,string> (); Set of key-value pairs
Dic. ADD (1, "Zhang San"); Adding the same key will throw an exception in this way
dic[2]= "John Doe" adds the same key in this way overwrites the value of the original key
A foreach loop for determining the set of key-value pairs
foreach (var item in collection)
{

}
foreach (keyvaluepair<int,string> kv in dic)
{
Console.WriteLine ("{0}------{1}", Kv.key,kv.value);
}
Console.readkey ();

File stream
The StreamReader of the File FileStream operation Byte StreamWriter the action character of the
Text and data are best placed under relative paths (in debug)
The code should be written in the using (), because its resources will not be automatically released, we must manually release, written in the using can help us to automatically recycle resources.
using (FileStream fsread = new FileStream ("Zucema.txt", FileMode.OpenOrCreate, FileAccess.Read))
{
byte[] buffer = new BYTE[1024 * 1024 * 5];
The number of bytes actually read to this read
int r=fsread.read (buffer, 0, buffer. Length);
Parses each element in a byte array into a string according to the encoding format we developed
String s=encoding.default.getstring (buffer, 0, R);
Console.WriteLine (s);
}
Console.readkey ();
If it's big data, you have to read it in a loop.

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 ("Write Success");
Console.readkey ();
Overwrite is by byte to overwrite
To use the additional words, change the filemode.openorcreate to Filemode.append is added.

Polymorphic
Let an object show a variety of states, types
Benefits of Write Polymorphism
1. Reduce the Code
2, shielding the differences between the various sub-categories, write out the common code, applicable to each subclass of code

Virtual methods and abstract classes

Declaring a parent class to specify a subclass object
Virtual Method Classic Example: Wooden ducks will bark, rubber ducks will bark, real ducks will bark, but they call the way different, real ducks are parents, meaningful, need to instantiate
The later use of the more is the abstract class

Access modifiers in the 2.c#
Public: Publicly available
Private: Only accessible within the current class
Protected: Protected, accessible only within the current class and in subclasses of the class
Internal: can only be accessed in the current project, in the same project, internal and public permissions are the same.
In the same project, internal has more permissions than protected. But once you cross the project, protected has more permissions than internal
Protected permissions for Internal:protected+internal

1), there are only two access modifiers that can modify a class: public internal
The default is not to manually add the public modifier to the class, then it is internal decorated by default

2), accessibility inconsistencies.
The subclass's access rights cannot be higher than the parent class's access rights, exposing the members of the parent class.
Because of the transitive nature of inheritance, a subclass can use a member of the parent class, but the parent class permission is written so that it cannot be accessed to a member by another project.

3. Design mode
Design is a way of this project
23 Different design modes
Design pattern is to help us solve the problem in the daily development.

4. Simple Factory design mode

5. Value types and reference types
Value types: int, double, char, decimal, bool, enum, struct stack
Reference types: String, array, custom class, collection, object, interface storage heap

Value passing and reference passing
When a value type is copied, the value is passed by itself.
When a reference type is copied, it passes a reference to the heap object.

6. Serialization and deserialization
Serialization: Converting an object to a binary
Deserialization: The conversion of a binary into an object
Function: transmits data.
Transfer data in the network, only binary this pattern can be transmitted.
Serialization:
1), Mark this class as serializable.
Mark a [Serializable] above the class, only the object to which it is marked can be serialized

Example: Serialization
To transfer the P object to the other computer
Person p = new person ();
P.name = "Zhang San";
P.age = 19;
P.gender = ' Male ';
using (FileStream fswrite = new FileStream (@ "C:\Users\SJD\Desktop\p.txt", FileMode.OpenOrCreate, FileAccess.Write))
{
Serializing objects
BinaryFormatter bf = new BinaryFormatter ();
Bf. Serialize (Fswrite, p);
}
Console.WriteLine ("Serialization succeeds");
Console.readkey ();

Deserialization
Receive the binary deserialized object sent by the other party.
Person p;
using (FileStream fsread=new FileStream (@ "C:\Users\SJD\Desktop\p.txt", FileMode.Open,FileAccess.Read))
{
BinaryFormatter bf = new BinaryFormatter ();
Object cast to Person
p= (person) bf. Deserialize (fsread);
}
Console.WriteLine (P.name);
Console.WriteLine (P.age);
Console.WriteLine (P.gender);
Console.readkey ();

7.partial Part Class
Three people doing a project together, everyone has to develop a person class. I can't write if you can't write.
Put a partial in front of each class, indicating that some classes
public partial class person
{
}
public partial class person
{
}
Indicates that the two classes together make up the person class, which can be written at the same time.
There is also a benefit, whether public or private, can be read to each other
Some classes do not have the same method, but can be overloaded, quite a class written in different places

8.sealed Sealing Class
Sealed is used to mark a class as a sealed class
public sealed class person
Feature: Sealed classes cannot be inherited by other classes, but can inherit from other classes

9. Overriding the ToString Method
Person P=new person ();
Console.WriteLine (P.tostring ());
Console.readkey ();
The printer will be the namespace of this object.

Why can all types be tostring?
Because all types of parent classes are object
Some of the methods provided in object can be called by subclasses.
ToString can call
ToString is the virtual method of object
So all variables of all objects can be called by ToString

10. Interface
Inherited attributes are single, and a subclass allows only one parent class
A subclass that wants to inherit 2 parent classes can be written as an interface
The keyword that declares the interface is interface
In English I start able and end all indicate ability

Interface is a specification, capability
Only by conforming to this norm can we survive.
Ability: Be able to actually a certain function.

Syntax and characteristics of interfaces
Format:
[Public] Interface I.. Able
{
Members
}

public interface Iflayable
{
void Fly ();
String Test ();
}
1. You can have a return value, use a string, and so on.
2. Members in the interface do not allow the addition of access modifiers, which is public by default
3. Interface members cannot have definitions and do not allow the writing of functions with method bodies
4. Interface cannot save data (field), save data with class to save
5. Can write method without method body (automatic attribute)
6. Methods, automatic attributes

Why call Automatic attributes
Although we do not write a segment, we will automatically generate a private field when we compile it.
To qualify it can only have constructors
public int Age
{
Get
Set
}

Automatic attributes are essentially two functions, one called get one called set

Methods and properties are generally put in an interface (essentially, only methods)

The access modifier is not added to the interface, and the default is public
Class does not add an access modifier, the default is private
Cases:
Manufacturer of notebook, no matter what manufacturer you are. Finally, you have to make a USB port. You can plug the mouse keyboard. are compliant with the USB specification. Each manufacturer must follow the specification. There are also special, such as apples, there is no cable mouth. Mobile phones are also tending to a norm.
When will the interface be used?
1, when the class needs more inheritance

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

For polymorphism.
The interface cannot be instantiated.
That is, the interface cannot be new (cannot create an object)

Members in an interface cannot have access modifiers, the member access modifier in the interface is public, and cannot be modified.


(Default to public)
The members of an interface cannot have any implementation ("Light says not to do", but define a set of non-implemented members, just like abstract classes, only inheriting their subclasses).

Interfaces can only have methods, properties, indexers, events, and cannot have fields and constructors.

Interfaces and interfaces can inherit, and can inherit more.

An interface cannot inherit a class, and a class can inherit an interface (an interface can inherit only from an interface, and a class can inherit an interface or inherit a class).


Subclasses that implement an interface must implement all members of the interface.


A class can inherit a class at the same time and implement multiple interfaces, and if a subclass inherits the parent class A and implements the interface IA, then syntactically a must be written in front of the IA.


Class myclass:a,ia{}, because classes are single-inheritance.


Display the purpose of implementing the interface: The problem of duplicate name of the workaround
When to display the go to implement Interface:
When the methods and parameters in the inherited interface are the same, use the displayed implementation interface

When an abstract class implements an interface, subclasses are required to implement the interface.


Object-oriented (interface) programming

11. Display Implementation Interface
Display implementation interface is to solve the problem of the name of the method

Cases:
public class Bird:iflyable
{
public void Fly ()
{
Console.WriteLine ("Bird will Fly");
}
void Iflyable.fly ()
{
Console.WriteLine ("I am the fly of the interface");
}
}

Iflyable fly=new Bird ();
Fly. Fly ();//Call is the fly of the interface

Bird bird=new Bird ();
Bird. Fly ();//This is the call of your own fly

12. Summary
When do you use virtual methods to achieve polymorphism?
When do you use abstract classes to achieve polymorphism?
When do I use interfaces to achieve polymorphism?

Among the classes I have given you, if you can abstract a parent class, and the parent must write the methods common to these subclasses, and then you do not know how to write this method, use abstract classes to write the polymorphic.
Conversely, the abstract parent class, the method can write, and I also want to create the object of the parent class, using virtual methods.
In these categories there is no parent class, but they all have a common act and common ability. This time using the interface to achieve polymorphism (metaphor: birds and airplanes there is no parent class, but will fly, there is no way to write a parent class let it inherit)

A real duck can swim, a wood duck can't swim, a rubber duck can swim.
No way to extract a parent class can swim, because wood ducks can't swim, no way to use virtual methods
There is no way to write abstract methods, because the real ducks need to be created objects, the real ducks make sense.
So the interface is the most suitable


13. Supermarket cashier System
A GUID can help us create a unique number in the world. does not repeat
Guid.NewGuid () can be ToString ()


Use the parent class to do the collection, shielding the differences, but not easy to find, all the goods are mixed together.
list<productfather> list = new list<productfather> ();
Storage of goods, collections to be deposited (as the goods will be increased)
list<sumsung> listsum = new list<sumsung> ();
list<acer> listacer = new list<acer> ();
list<jiangyou> listjiangyou = new list<jiangyou> ();
list<banana> Listbanana = new list<banana> ();
list<list<productfather>> List = new list<list<productfather>> ();
I put a collection in a collection.
The content inside the list<> should be the type of the collection.
list<productfather> list2 = new list<productfather> ();
The difference between the two:
When adding data to List2, it is possible to add the object directly, such as Samsung, mobile phone, notebook, soy sauce, can be directly thrown in the collection.
The disadvantage is that it is troublesome to take. Saved in, do not know which subscript is who, have to go through the debugging to see. It's troublesome to look at the data of the subscript.

So we use 2 sets, 2 sets what does that mean?
When adding data to a list
List. Add () adds a collection in. Actually, this collection is the shelf.
Add data to him, add not goods, but shelves
Both the list and the List2 represent the entire warehouse.

Adding a warehouse with List2 is to take this data back and throw it directly into the warehouse.
The list is to add a collection of arrays, which adds a collection of data to the warehouse, and the warehouse goods are concentrated on the shelves
The shelf is a collection of goods (shelves are put goods), add shelves, there are four shelves, so add four elements come in.

list<list< Parent class >>list=new list<list< parent >> ();
list[0]= Shelves
What kind of a product's parent can you put in?
Add the goods to the warehouse, actually to list[0],list[1],list[2] ....
This way you can get to the shelf where the goods are.

In the warehouse, in addition to goods and shelves is also a collection
The above only created the warehouse, there is no shelf

When do I create a shelf?
Add shelves to the warehouse when creating Cangku objects

Cases:
Use the parent class to do the collection, shielding the differences, but not easy to find, all the goods are mixed together.
list<productfather> list = new list<productfather> ();
Storage of goods, collections to be deposited (as the goods will be increased)
list<sumsung> listsum = new list<sumsung> ();
list<acer> listacer = new list<acer> ();
list<jiangyou> listjiangyou = new list<jiangyou> ();
list<banana> Listbanana = new list<banana> ();
list<list<productfather>> List = new list<list<productfather>> ();
LIST[0] Store Acer computers
LIST[1] Store Samsung phones
LIST[2] Storage soy sauce
LIST[3] Store Bananas
<summary>
Add shelves to the warehouse when creating objects 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 mask the differences of each shelf
Many shelves are used for loops
for (int i = 0; i < 4; i++)
{
List. ADD (New list<productfather> ());
}
}
<summary>
Purchase
</summary>
<param name= "Strtype" > Types of Goods </param>
<param name= "Count" > Quantity of Goods </param>
public void Getpros (string strtype,int count)
{
A lot of goods, one add not finish, through the For loop to add
for (int i = 0; i < count; i++)
{
Strtype There are four possible types of cargo, so make a multi-conditional judgment on it
Switch (strtype)
{
Case "Acer": list[0]. ADD (New Acer (GUID.NEWGUID). ToString (), 1000, "Acer Base Notebook"));
Break
Case "Sumsung": list[1]. ADD (New Sumsung (GUID.NEWGUID). ToString (), 2000, "Stick Mobile"));
Break
Case "Jiangyou": list[2]. ADD (New Jiangyou (GUID.NEWGUID). ToString (), 10, "old smoked soy sauce");
Break
Case "Banana": list[3]. ADD (New Banana (GUID.NEWGUID). ToString (), 50, "Big Banana");
Break
}


}


Methods of extracting goods
<summary>
Extracting the goods from the warehouse
</summary>
<param name= "Strtype" ></param>
<param name= "Count" ></param>
<returns></returns>
Returns a collection or array of parent classes
Public productfather[] Qupros (string strtype, int count)
{
Put the goods into the array to return
productfather[] Pros = new Productfather[count];
The stock is a one to put in, pick up is also a one to take out
for (int i = 0; i < count; i++)
{
Switch (strtype)
{
On the shelf the first [0], after taking away, the second one on top to become the first [0]
It's just an assignment, and the number on the shelf hasn't changed.
LIST[0] is the Acer notebook of that shelf, list[0][0] is the first notebook on the shelves, and then placed in the pros array
Case "Acer":
Determine if the shelves are empty
if (List[0]. Count = = 0)
{
Break
}
Pros[i] = list[0][0];
Remove the first one, take a delete one
List[0]. RemoveAt (0);
Break
Case "Sumsung":
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 collection

}
Return pros;
}

And a way to show the goods.


13. Summary
Value passing and reference passing values are passed by the value itself.
Reference passing is a reference to an object
Ref: Change the value pass to a reference pass (not necessarily right)
Syntax features of interface interfaces
Display Implementation Interface
When do I use the interface?
Partial class (partial)
Sealing Class (sealed)
Serialization and deserialization purpose: transferring data
Simple Factory design mode
Access Modifier 5 access modifier

C # Basic notes (13th day)

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.