Past few days C # object-oriented <3> 〉,

Source: Internet
Author: User

Past few days C # object-oriented <3> 〉,
C # Basic Methods

I. Review
1) method Overloading
Method Overloading is not a method. In fact, method Overloading is a number of different methods. The purpose is to facilitate coding, so similar methods have the same name.
According to the parameters, the compiler automatically de-matches the method body, without the programmer's need to remember the method.
-- "How to judge whether the reload write is correct
Remove the method definition, modifier, method body, and return type.

int InputNum()int InputNum(int max)int InputNum(int min,int max)

--> Remove the local variable name from the parameter list, leaving only the parameter type

int InputNum()int InputNum(int )int InputNum(int ,int )

Ii. Encapsulation
-"Attribute" is the encapsulation of fields.
-The method is encapsulation of the process
-Class: encapsulation of objects (features and functions)
-Assembly is the encapsulation of Class Libraries

C # basic inheritance

Why use inheritance?
-Code reuse
-"Realize polymorphism (Lishi conversion)

In inheritance, classes are divided into parent classes (base classes) and child classes (derived classes)

Base Class

Write this class with common features separately, called the parent class (base class)

Subclass

Inherit all features of the parent class, and you can also have different features of your own.

Parent class (base class): encapsulates some features and behaviors of objects in this class into this class.
Then this parent class is derived from the subclass (derived class), which inherits the features (attributes) behavior (methods) in the parent class. This allows code to be reused.
For example:

Class Person {string _ name; int _ age; char _ sex; public string Name {get {return _ name ;}} public int Age {get {return _ age ;}} public char Sex {get {return _ sex;} public Person (string name, int age, char sex) {_ sex = sex; _ name = name; _ age = age;} public void SayHello () {Console. writeLine ("Hello everyone, my name is {0}. I'm {1} years old. I'm {2} student", _ name, _ age, _ sex );}} class student: Person {public student (string name, int age, char sex): base (name, age, sex) {// method body} public void SayHello () {Console. writeLine ("Hello everyone, my Name is {0}. I'm {1} years old. I'm {2} student", Name, Age, Sex );}}


The student class is the derived class of person. It inherits all the members of the person class, including the SayHello method. The Student sayhello method hides the sayhello method of the parent class.
Inherited features
-Single Root feature (only one base class can be inherited)
-"Passed" (Child classes can inherit the members of the base class. Fields, attributes, and methods)
-"Derived from the object root class (based on C #) (why is there a root class? Or to realize polymorphism)

Notes
-Constructor
When creating an object, it seems that the subclass constructor is called first, and then the subclass calls the parent constructor,
When you call the constructor, there is actually a base () by default, which calls the non-argument constructor of the parent class.

Syntax:
Class base class
{
// Base class member
}
Class subclass: base class
{
// Sub-classes can have their own members
// The member of the base class will also be inherited.
}
Execution sequence of child classes in the parent class Constructor
Student student = new Student ();
Here, the New subclass object will first go to the subclass construction method. Here, the system will provide a base () construction method without parameters by default. If the parent class has a constructor with parameters, the system will not assign a constructor without parameters,
In this case, if the subclass calls the constructor of the parent class, an error is returned because the non-argument constructor of the parent class is no longer available. The solution consists of two
1) then manually add a construction method without parameters to the parent class.
2) base (parameter list) transmits parameters.
Public student (string name, int age, char sex): base (name, age, sex) does not execute the following braces here, and then base calls the constructor of the parent class, if there is a parent class above the parent class, it will be upgraded in sequence,
Until the top parent class is adjusted to the top parent class, the top parent class constructor is executed, and then the next class is executed in sequence to return to the Child class, and the remaining method bodies are executed.
{
// Method body
}
This and base keywords:
This indicates the current constructor of the current class.
Base indicates the parent class constructor.
Classic example:

class MyClass    {        public MyClass():this(3)        {            Console.WriteLine(1);        }        public MyClass(int i):this(2,3)        {            Console.WriteLine(i);        }        public MyClass(int i, int j)        {            Console.WriteLine("{0}{1}",i,j);        }    }    class Program    {        static void Main(string[] args)        {            MyClass myclass = new MyClass();        }    }


When a new object is created, it first jumps to the constructor without parameters. At this time, we can see this (3), without executing the method body. In this class, we will find a constructor that matches a parameter, then,
At this point, we can see this (). In this class, we can find the constructor that matches two parameters, call the constructor with two parameters, and execute the method body with two parameters,
After completion, return to the constructor with a parameter to execute the method body of the constructor without parameters.

C # basic Polymorphism

4. Access Modifier
Privete is only accessible in this class
Public can be accessed anywhere
Protected can only be accessed in the current class and subclass
Internal only allows access in the current class
Protectecd internal
Lishi Conversion
1) subclass can be directly assigned to the parent class (subclass objects can be directly converted to parent class objects) for implicit conversion
2) If the parent class object meets the first condition, it can be forcibly converted to the original subclass object. Forced conversion
Forced conversion can be determined by the is and

Is:
Syntax bool B = the object to be converted is the type to be converted
If the conversion is possible, a true value is returned. If the conversion is invalid, a false value is returned.
The IS operator IS clear, but the operation efficiency IS not high. The other method IS

As:
Type object to be converted by syntax = type object to be converted as type to be converted
The as operation first tests whether the operation is legal. If the operation is legal, the conversion is performed. If the operation is illegal, null is returned. null indicates a null reference.

V. new and override
New hides the base class method: the premise is that the return value of the method name parameter of the subclass and parent class is the same. At this time, there is no difference between writing new and not writing new.

Class MyBase {public void Func () {Console. writeLine ("I am a parent class");} class MySub: MyBase {public void Func () {Console. writeLine ("I Am a subclass ");}}

At this time, the subclass method will hide the method of the parent class. At this time, the method of the object type will be called.

Override base class method: The subclass must override the base class method, and the parent class method must have virtual representation, which can be overwritten by the quilt class.
Once the method of the parent class is overwritten, the method of the parent class will no longer exist, and the new method after rewriting will be called.

C # Call the constructor

Class Person // base class human
{

// How to access the fields of the parent class in the subclass

// Define the attributes of three fields.

// Set the field access modifier to protected so that the field can be accessed in the subclass.

// Protected indicates that the current class and subclass can be accessed.


protected string _name;public string Name{get { return _name; }}protected int _age;public int Age{get { return _age; }}protected char _gender;public char Gender{get { return _gender; }}

// Write a constructor to initialize and assign values to Fields

public Person(string name, int age, char gender){this._name = name;this._age = age;this._gender = gender;}

// Define a constructor without parameters so that the Child class can call the constructor of the parent class to avoid errors when the child class calls the constructor without parameters.

public Person(){}}

// Define a supperman subclass inherited from person

Class SupperMan: Person {// unique field feature of the subclass private string _ state; public string State {get {return _ state;} public SupperMan (string name, int age, char gender, string state) // here, if no base () is specified, the constructor of the parent class without parameters is called by default. The write and write operations are the same {base. _ name = name; base. _ age = age; base. _ gender = gender; base. _ state = state; // * this indicates that this is a field in this class. // * base indicates that this is a field inherited from the parent class. // * Here this and base can be left blank and written to programmers.} public void Hello () {Console. writeLine ("Hello everyone, my Name is {0}. My Age is {1}. I am {2} people. My characteristics are {3}", Name, Age, gender, State) ;}} class Program {static void Main (string [] args) {SupperMan supperMan = new SupperMan ("Superman", 28, 'male ', "underpants"); supperMan. hello (); Console. readKey ();}}
C # basic Constructor

2) constructor
-- There is no inheritance relationship
-"Default constructor (constructor without parameters)
When no constructor is provided, the system automatically adds a constructor without parameters.
If the constructor has been written, the system will not automatically add the default constructor (manually add)
-"Constructor methods are also overloaded.
Call
This (when there is this after a constructed method is called, the overload indicated by this is called first, and then its own constructor is called)
-- Has an inheritance relationship
-By default, the constructor of the parent class is called.
-Using base, you can specify to call the parent class constructor.

Static Constructor
The static constructor is called and executed only once from the beginning to the end of the program. It is called and executed when a new object or a field or attribute accessing this class is used,

C # enhanced basic Polymorphism

Prerequisites for implementing polymorphism:
-"Inherit"
-The sub-class parent class method name must be the same
Lee's conversion principle (only one condition for realizing polymorphism is not a prerequisite)
-Parent class Object = new subclass ();
...
Subclass subclass object = (subclass) parent class object must meet the preceding conditions before conversion is successful
Hiding base classes
You only need to write the new Keyword before the subclass method (you can also leave it empty and the system will automatically add it)
Hide viewing type

Class Person {public void SayHello () {Console. writeLine ("yi ah") ;}} class American: Person {public new void SayHello () {Console. writeLine ("Hello") ;}} class Korean: Person {public new void SayHello () {Console. writeLine ("Ah, you, ha sa ");}}

Override base class Method
-Add virtual
-Add override to the subclass Method
Rewrite new


Class Person {public virtual void SayHello () {Console. writeLine ("yi ah") ;}} class American: Person {public override void SayHello () {Console. writeLine ("Hello") ;}} class Korean: Person {public override void SayHello () {Console. writeLine ("Ah, you, ha sa ");}}


Ii. generate random numbers
Random: a class that specifically processes Random numbers. (Pseudo-random number, the operating principle is: first obtain the current time of the system (accurate to milliseconds), and then calculate a number (so-called pseudo-random number) according to the current time of the system ))
-- Create a random object
Random r = nrw Radom ();
Note: Do not create random number objects in a loop. Otherwise, you will get repeated numbers.
--> Call the Next method to obtain the random number.
-The next method has three reloads.
Int res = r. netx (); generates a non-negative random number.
Int res = r. next (100); generates a random number ranging from 0 to 99.
Int res = r. next (); generates a random number between 2 and 29. The two ends can obtain

Time record class
Stopwath:
Stopwath stop = new Stopwath ();
Stop. start (); start Calculation
.....
Stop. Stop (); stop computing

Console. writeLine (stop. Elapsed );

Polymorphism: For program scalability
-Principle of opening and closing (open to expansion and closed to modification)
Use of polymorphism:
Consider different objects as parent classes, block the differences between objects, write common code, and make general programming,
Iii. abstract classes
What is an abstract method?
Sometimes the methods of the parent class do not need to be implemented.
Sometimes I don't know how to implement it.
A method without a method body is called an abstract method, which is modified using abstact,
Classes that contain abstract methods must also be an abstract class.
Abstract classes can contain non-Abstract members.
The usage of abstract methods is exactly the same as that of virtual methods.
The difference is that their definitions are different. abstract classes cannot be instantiated.
Abstract classes exist to be inherited, so they cannot be defined as private.

Abstract classes cannot be instantiated. They have more abstract members than general classes.
Abstract classes and general classes have two major differences
-- Cannot be instantiated
-- Has abstract members (all methods can be abstracted)
-"Method
-"Attributes
-"Indexer (attributes with parameters)
-"Event Declaration (this can be viewed as" attribute ". The attribute is a get set method, and the event is the add remove Method)

When abstract attributes are used, abstract classes generally provide attributes and accessibility.
Subclass provides the implementation of fields and attributes
Public abstract string s
{
Get; // The attributes here look very similar to the automatic attributes, but note that they have different meanings. Here, abstract modifier tells the system that there is no method body for abstract methods, so you do not need to write {} here {}
Set; // The abstract attribute can only be get or set, because it can assign values to the field by the constructor, and the automatic attribute is automatically generated in the background, so the get set of the automatic attribute must appear in pairs.
}

C # basic rewrite ToString Method

4. Override the ToString Method

String [] str = {"1", "2", "3", "4"}; MyClass myClass = new MyClass (); myClass. name1 = "I am MyClass"; myClass. name2 = "0"; myClass. name3 = "3"; myClass. name4 = "4"; myClass. name5 = "5"; MyStruct myStruct; myStruct. name = "My Name is MyStruct"; Console. writeLine (str); Console. writeLine (myClass); Console. writeLine (myStruct );

The system will call the ToString () method by default to print arrays and classes. There is a ToString () method for any type, because this method is provided by the object root class, all classes in C # are inherited from the object class, so the ToString () of the object will be inherited.
Reflector you can see that the ToString () method of the object is a virtual method. If the subclass is not overwritten, the system will call this method by default,
You can see that this method calls this. GetType () method (obtain the namespace of the current strength), and then returns
Therefore, The namespace name and Instance name of the instance are printed above.

public virtual string ToString()   {    return this.GetType().ToString();   }

Since the parent class provides a virtual method, the subclass can be rewritten. We can use the subclass to override the ToString () method to implement the content we want to display.

Class MyClass {public string name1; public override string ToString () {return name1 ;}} class Program {static void Main (string [] args) {MyClass myClass = new MyClass (); myClass. name1 = "zhangsan"; Console. writeLine (myClass); // three consoles are displayed here. readKey ();}}

// This series will be updated continuously. Good night!


 

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.