3. C # object-oriented: encapsulation, inheritance, polymorphism, String, set, file (bottom ),

Source: Internet
Author: User
Tags object serialization

3. C # object-oriented: encapsulation, inheritance, polymorphism, String, set, file (bottom ),

Object-oriented Polymorphism

I. packing and unpacking

Packing: Convert the value type to the reference type. Object o = 1; Value Type assigned to reference type

Binning: converts a reference type to a value type. Int n = (int) o; forced conversion to Value Type

Conditions met: whether there is an inheritance relationship between the two types.

Int n = Convert. ToInt32 ("12"); no packing or unboxing occurs. Int is stored in the stack, string is stored in the heap

Packing or unpacking may affect program running events.

2. Object-oriented Polymorphism

Multiple States are displayed when an object calls the same method.

1. Virtual Methods

Mark the method of the parent class as a virtual method and use the keyword virtual. You can re-write the method of the quilt class.

 

Protected void Page_Load (object sender, EventArgs e) {person [] p = new person [2]; chinese p1 = new chinese (); jpan p2 = new jpan (); p [0] = p1; p [1] = p2; Response. write (p [0]. sayHi (); // The method called depends on the object Response. write (p [1]. sayHi ();} public class person {public virtual string SayHi () // The parent class method uses virtual to indicate that this method is a virtual method {return "human ";}} public class chinese: person {public override string SayHi () // The subclass method uses override to overwrite the virtual method {return "" ;}} public class jpan: person {public override string SayHi () // override {return "Japanese ";}}

 

2. abstract class

When the methods in the parent class do not know how to implement them, you can enter the parent class as an abstract class and the methods as abstract methods.

Abstract classes are defined as abstract classes, abstract methods are defined as abstract methods, and abstract functions have no method bodies.

The abstract class cannot instantiate the parent class. It is called directly by instantiating the subclass.

The virtual method is used when the parent method is meaningful, and the abstract class is used when the parent method is meaningless.

Protected void Page_Load (object sender, EventArgs e) {// The abstract class cannot be instantiated. Only the subclass object xingzhuang y = new yuan (5) can be instantiated. double mianji = y. mianji (); double zhouchang = y. zhouchang (); Response. write ("the prototype with a radius of 5 is:" + mianji + ", perimeter:" + zhouchang); xingzhuang ju = new juxing (10, 20); double mianji1 = ju. mianji (); double zhouchang1 = ju. zhouchang (); Response. write ("the rectangle with a width of 10 and 20 is:" + mianji1 + ", perimeter:" + zhouchang1);} publ Ic abstract class xingzhuang // The class marked as abstract is called the abstract class {public string Name {get; set;} // The abstract class can contain instance members, and the strength members can be implemented without the quilt class. Public abstract double mianji (); // abstract methods must be marked as abstract, and cannot have any implementations. They must be in abstract classes. Public abstract double zhouchang (); // The access modifier of the abstract member cannot be private} public class yuan: xingzhuang {public double R {get; set;} public yuan (double r) {this. R = r;} public override double mianji () // After the subclass inherits the abstract class, all abstract members in the parent class must be overwritten {return Math. PI * this. R * this. r;} public override double zhouchang () // After the subclass inherits the abstract class, all abstract members in the parent class must be overwritten {return 2 * Math. PI * this. R ;}} public class juxing: xingzhuang {public double width {get; set;} public double height {get; set ;} public juxing (double height, double width) {this. height = height; this. width = width;} public override double mianji () // After the subclass inherits the abstract class, all abstract members in the parent class must be overwritten {return this. height * this. width;} public override double zhouchang () // After the subclass inherits the abstract class, it must overwrite all abstract members in the parent class {return (this. height + this. width) * 2 ;}}

3. Simple Factory Design Model

Class Program {static void Main (string [] args) {while (true) {Console. writeLine ("Enter the disk to enter"); string path = Console. readLine (); Console. writeLine ("Enter the file to enter"); string fileName = Console. readLine (); FileFather f = getFile (fileName, path + fileName); f. openFile (); // open a file depends on the input file Console. readKey () ;}} public static FileFather getFile (string fileName, string fullName) // return the parent class {string ext = Path in simple factory format. getExtension (fileName); FileFather f; switch (ext) {case ". txt ": f = new txtPath (fullName); break; case ". jpg ": f = new jpgPath (fullName); break; default: f = null; break;} return f ;}} public abstract class FileFather // abstract parent class {public string fileName {get; set;} // The full file path public FileFather (string fileName) // The constructor cannot use {this. fileName = fileName;} public abstract void OpenFile (); // abstract method} public class txtPath: FileFather {public txtPath (string fileName) // inherits the parent class constructor: base (fileName) {} public override void OpenFile () // rewrite the subclass {ProcessStartInfo psi = new ProcessStartInfo (fileName ); // use the Process to open the specified file Process pro = new Process (); pro. startInfo = psi; pro. start () ;}} public class jpgPath: FileFather {public jpgPath (string fileName): base (fileName) {} public override void OpenFile () {ProcessStartInfo psi = new ProcessStartInfo (fileName); Process pro = new Process (); pro. startInfo = psi; pro. start ();}}

Iv. Value Transfer and reference Transfer

Value Type: int double char decimal bool enum struct stored on Stack

Reference Type: string Array custom class set object interface stored in heap

Value Transfer: int n1 = 10; n2 = n1; n2 = 20; when the value type is assigned, the value itself is passed and copied. P1 = 10; p2 = 20;

Reference transfer: p1.name = "3"; p2.name = p1.name; p2.name = "4"; when the reference type is assigned, the reference of this value is passed, referencing the same copy, p1 p2 points to the same memory.

V. serialization and deserialization

Serialization: convert an object to binary

Deserialization: Convert binary data to an object

Purpose: transmit data.

1. Mark this class as Serializable.

2. Use BinaryFormatter to start Object serialization.

Protected void Page_Load (object sender, EventArgs e) {// transmit P to the peer computer person p = new person (); p. name = "James"; p. age = 18; p. gender = 'male'; using (FileStream sw = new FileStream (@ "d: \ 11.txt", FileMode. openOrCreate, FileAccess. readWrite) // serialize to the target file {// start to serialize the object BinaryFormatter bf = new BinaryFormatter (); bf. serialize (sw, p); // sw of the object to be serialized. write Automatic completion} person per = new person (); // receives the binary deserialization object using (FileStream sr = new FileStream (@ "d: \ 11.txt", FileMode. openOrCreate, FileAccess. readWrite) {BinaryFormatter bf1 = new BinaryFormatter (); per = (person) bf1.Deserialize (sr);} Response. write (per. name + per. age + per. gender);} [Serializable] // mark this class as public class person {public string name {get; set;} public int age {get; set ;} public char gender {get; set ;}}

6. partial Classification

The local type allows us to divide a class, interface, or structure into several parts, which are implemented in several different. cs files respectively.

Public partial class person
{
}
Public partial class person
{
}

1) The type is very large and should not be implemented in a file.

2) You need to work with multiple people to compile a class.

7. sealed

The sealed class cannot be inherited. Therefore, it cannot be an abstract class.

Override ToString ()

Subclass overrides the virtual method of the parent class

Public override string ToString () {return "sd ";}

VIII. interface

An interface is a standard and a reference type. Because only one inheritance can be inherited, multiple inheritance can be implemented through the interface.

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

The interface cannot be instantiated and cannot be new.

When declaring an interface member, you are not allowed to write specific executable code for the interface member.

Interfaces can be inherited from each other. interfaces can be inherited from each other.

The interface members cannot have static, abstract, override, and virtual modifiers. When using the new modifier, no error is reported, but a warning is given that the keyword new is not required.

A class inherits the interface and the class. In syntax, the class must be inherited before the interface

Public interface IFly {// members are not allowed to add access modifiers. The default value is public string name {get; set;} // The interface can have methods, properties, and cited devices. Void Fly (); // method body not allowed} public class father {} public class person: father, IFly // write the class first and then write the interface {public string name {get; set ;}public void Fly (){}}

Display Interface

 

// Used to solve the problem of duplicate names. class Program {static void Main (string [] args) {Ifly fly = new Birad (); fly. fly (); // Briad bid = new Briad (); bid of the interface. fly (); // your own} public class Birad: Ifly // ifififly {public string Fly () // your method {return "fly ";} public string Ifly. fly () {// interface method return "ifly11111" ;}} public interface Ifly // define the interface fly method {string Fly ();}

 

IX. Handling exceptions and exceptions

Try {int number = 10; // code block that may cause an error} catch (Exception ex) {Console. writeLine (ex. message); // error Message throw new Exception ("error"); // throw an Exception}

1. When can I use the virtual method to implement polymorphism?

A parent class can be extracted, and the explicit method needs to be written.
2. When can I use abstract classes for polymorphism?

You can extract a parent class, but you do not know how to implement it.
3. When can I use interfaces to implement polymorphism?

A parent class cannot be extracted, but there is a common behavior, or multiple inheritance is required.

What is the use of interfaces for polymorphism?

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.