C # Object-oriented niche learning

Source: Internet
Author: User

One: object-oriented basics

C # programs are divided into process-oriented and object-oriented

What is an object: Everything is objects: object, life is often said "things" is the object of the program, the things we encounter in life are subconsciously categorized; classification implies abstract models;

Class: A model that is abstracted from the common features of a class of many objects.

Their relationship: A class is an abstraction of many objects, and an object is an instantiation of a class.

Create a class named Dog:

Class Dog  //General initial capital letter    {       int age;       public void Setage (int a)//assignment with method        {Age           = A;        }       public void Buck ()        {            Console.WriteLine ("This is a method");        }    }

Classes generally include two kinds of things, variables (nouns, also cross member variables, where age is a member variable) and functions (verbs, also called member functions or Member methods, Buck () is the method).

Object instantiation:

Dog D1 = new Dog ();

This instantiates a dog's object A.

Example: two sets of circles together, the circumference of the inner circle and the area between the inner circle and the outer circle, with the object-oriented thinking to do

Class Circle    {        float R;        Public Circle (float a)        {            r = A;        }        Public double Zhouchang ()        {            return 2 * 3.14 * r;        }        Public double Mianji ()        {            return 3.14 * R * r;        }    }    Class program    {        static void Main (string[] args)        {            Circle m = New Circle (ten);            Circle n = new Circle (a);            Double BC = M.zhouchang ();            Double MJ = (N.mianji ()-m.mianji ());            Console.WriteLine ("The circumference of the inner circle is:" +BC);            Console.WriteLine ("The area of the tile is:" +MJ);}    }

First, a class called Circle, which can produce any circle with a different radius, is assigned a radius in the constructor.

Two: Object-oriented three major features

Three major characteristics are: encapsulation, inheritance, polymorphism.

The methods in the class are generally divided into: Construction method (function), attribute method (function): Member variable assignment value, behavior method (function): variable operation.

(a): Package

1. Package Meaning:

(1) Variables of different classes belong to their respective classes only.

(2) member variables of different objects belong to their respective objects and are not affected by each other.

(3) The variables in the object need to be implemented by means of methods (functions), which is more secure.

Encapsulation for security, as far as possible without public to declare variables, avoid in the main function can directly access the assignment and reduce security, the method of establishing public in the class to assign a value, in main call this method to pass the value.

2. member variables and access modifiers

Private privately owned member, protected protected member, public member

3. Constructors

It is a special member function that is typically initialized in a constructor. If the constructor is not written, a default empty constructor is automatically generated when new.

Special: No return value, function name can only be the same as the class name; public class name () {};

Execute Special: The class is executed automatically when instantiated (new comes out), the constructor is the first member function to execute, and the constructor is the function used to generate the object.

Its main role: When object instantiation is generated, do some initialization work.

The following example is a constructor of the Ren () that assigns the initialized value to its variable:

Class Ren    {        string _name;        int _age;        Public Ren ()        {            _name = "Dragon God";            _age = +;        }    }

4. Overloading (functions or methods)

Multiple functions with the same function name and different parameters (with different number of arguments or types) Form an overload.

Overloading is only related to function names and formal parameters, regardless of return type.

Here's an example of the overload of the constructor:

    Class Ren ()        {            string _name;            int _age;            Public Ren ()            {                _name = "ZSMJ";                _age = +;            }            Public Ren (string name)            {                _name = name;            }            Public Ren (String Name,int age)            {                _name = name;                _age = age;            }        }

In this way, three constructors are made in the Ren class, the first one is parameterless, the second is a string type argument, and the third is a two parameter, and the type is string and int, respectively. They conform to the overloaded conditions, so it will be overloaded in the main function when new is automatically selected to execute one of the constructors, depending on the argument.

If you are in the main function:

ren a = new ren ("King Sledgehammer");

The constructor that executes is the second one.

5. Properties

Its declaration: The public Type property name, or you can select the member variable right-click Refactoring, encapsulate the field to generate the property method, for example:

    string _name;    public string Name   {      get {return _name;}      set {_name = value;}   }

So name is a property of the class, and in the main function you can use this property to assign values to its member variables:

     ren a = new ren ("King Sledgehammer");     A.name = "Wang Nima";

Note: (1) A property is used to assign values and values to a member variable, and it has the function of substituting an attribute method, typically with a property.

(2) When the attribute is defined, there is no parenthesis after the property name.

(3) Properties are public.

(4) The attribute can contain only two parts: Get and set. The code can only be written in the curly braces of get and set.

(5) Attributes are divided into read-only properties, write-only properties and read-write properties, and have no relation to get and set.

6. This keyword

Concept: This reference, which object inside which the this is executed represents the object itself.

Usage: this. Member variable (member method), This._name; This. Eat ();

Example: This invokes other constructors for the current object.

  public class mydate    {        int _year;        int _month;        int _day;        int _hours;       Public MyDate (Int. year,int Month)        {           _year = year;           _month = Month;       }       Public mydate (Int. year,int month,int day,int hours): This (year,month)       {           _day = day;           _hours = Hours;       }    }

Here the first constructor has two parameters year and month, in order to facilitate the use of ": This" in the second constructor to invoke the first constructor in this class, so that the second constructor only need to write the day and hours execution statements on it.

When you pass in a different parameter at new, the object is instantiated, and this represents a different object.

7. is keyword (operator)

Usage: object is class name; is left is object, right is type;

Console.WriteLine (A is Ren);

If a is an object of the Ren class, the return value is true, otherwise the return value is false.

8. Partial keyword

If a class is particularly large, it should not be implemented in a file or there is a part of the code in a class that should not be confused with others or require multiple people to work on a class, which requires a class to be written apart.

With the partial keyword can be implemented, can also be used to complement the perfect class, extensibility is strong. As in a file in the assembly, the partial class ren{is a member}, and the Ren class can be supplemented in another file, which is required to write the partial class ren{inside the member}. 9. Static Members

A non-static variable is called an instance variable, and a non-static method is called an instance method, and the data for the instance member is in each object and is invoked with the object name.

Static members include: Static variables, static properties, static methods.

Defines a member as static: Adds static to the variable or method, such as: Static int A;

Static variables belong to the class, each object has and the same thing is saved only one copy, not the same as the instance variable in each object to save a copy.

It can be said that it does not belong to any object, it can also be said that it belongs to any object, to each object, save space.

For example: The color of each package of chalk is a static member, and the remaining length of each piece of chalk is instance member.

Static variables or methods do not need to be new.

In C #, a class of chalk is defined:

   Class Fenbi   {       static string _color;    public static string Color    {      get {return fenbi._color;}      set {Fenbi._color = value;}    }       int _lenght;    public int lenght    {      get {return _lenght;}      set {_lenght = value;}    }     }

(1) Outside the curly braces of the current class, a static member can only be called with the class name, cannot be called with the object name, and the instance member can only be called with the object name and cannot be called with the class name.

      Fenbi.color = "Yellow";      Fenbi B = new Fenbi ();      B.lenght = 10;

(2) within the curly braces of the current class, a static method can call only a static member, cannot invoke a non-static member, and an instance method may invoke a non-static and static member.

     public static void Xiezi ()       {           Console.WriteLine ("Writing Out" +_color+ ");       }
     public void Change ()        {            Console.WriteLine (_color+) The chalk length changes to: "+_lenght);         }

10. Copy

Shallow copy: Pass a reference, not assign a value object.
Deep copy: Creates a new object.

(ii): Succession

1. Syntax: Public subclass Name: parent class name, such as: Class Dog:pet.

2. Features: Single inheritance, a parent class can derive multiple subclasses, but only one parent class per child class

If a class does not explicitly specify who the parent class is, the default is object. In addition to the object class, all classes have a parent class.

Subclasses can inherit the member variables and member methods of the parent class from the parent class.

3. Access adornments meet access rights:

Private members are not inherited and can only be accessed in this class.

Protected members can be inherited, accessible in this class and derived classes, and not accessible outside the world. The variables in the parent class are generally protected.

Public members can be inherited and accessible from all locations.

4. Base keyword: A subclass can be used (a member in a parent class) to invoke a member of the parent class, base () calls the parent class construct, and Base.xxx () invokes the parent class member method.

The parameter value of the call is overwritten and the method is overwritten.

5. The process of instantiating subclasses in an inheritance relationship:

Execute the constructor of the parent class first, and then the constructor of the child class.

6. Instantiation of an inheritance relationship:

If the constructor for the parent class does not have an empty parameter constructor, all with parameters, the subclass must write the constructor, the constructor must contain the parameters required by the parent class constructor, and the parameters required by the parent class constructor are passed to the parent class using base ().

For example: only this constructor in the parent class

      Public Ren (string name, Int. age)      {          _name = name;          _age = age;      }

Then the constructors in the subclass should write like this:

      Public Chinese (string name, int age, String Yuyan): Base (name,age)        {            _yuyan = Yuyan;        }

7. Sealed keywords:

This class cannot be inherited if it is used to modify a class, called a sealed class, and cannot be overridden if it is used to decorate a method.

such as: Sealed class ren{};

(c): polymorphic

1. Concept: When a parent refers to a different subclass instance, the parent class references the function that is called a subclass, and because the subclass object is different, the members of the calling member of the parent class represent a polymorphic state.

2. How to implement: polymorphism needs to be implemented by inheritance

3. Classification: Divided into compiled polymorphic (overloaded overload) and run Polymorphic (override override). After the parent class method is overridden, it can also be called with the base. method in the subclass.

4. Virtual Keyword: Virtual method, allow overrides, to override the parent class method must be a virtual method: public virtual void Eat ().

5. Conditions for running a polymorphic implementation:

(1) subclasses override (override) The parent class method, which has the same method in both the parent and child classes.

(2) The parent class reference points to the subclass instance.

For example, there is a Ren class that is a parent class, a Chinese class and a American is a subclass, Ren r = new Chinese (), and the parent class references R to the child class instance.

    Class Ren    {        protected string _name;        protected string _country;        public virtual void Eat ()        {            Console.WriteLine ("Eating ...");}    Class American:ren    {public        override void Eat ()        {            Console.WriteLine ("Eating with forks and knives ....");    }    class Chinese:ren    {public        override void Eat ()        {            Console.WriteLine ("Eating with chopsticks ...");        }    }

There is a eat method in parent Ren that is a virtual method, overridden in subclasses Chinese and American, in the main function:

    Random rand = new Random ();    int n = rand. Next (+);    Ren A;    if (n% 2 = = 0)    {        a = new American ();    }    else    {        a = new Chinese ();    }    A.eat ();

Randomly let the parent class reference A to different subclass instances, so that the parent class refers to a call method Eat () to show the operation of different objects.

6. The principle of substitution on the Richter scale and the principle of abstraction

On the Richter substitution principle, if a method receives a parent class reference, it can pass the element of the parent class or its child class to it, and the subclass object overrides the parent class object.

Abstract dependency principle, which points to an instance of a subclass with a reference to the parent class.

Example: Monster Eater, the reference to Ren's R, R. Cry () shows different results.

Class Monster    {public        void Eatfood (Ren r)   //r = A;        {            r.cry ();            Console.WriteLine ("Man is so delicious, he's full!") ");        }    }    Class Ren       {public        virtual void Cry ()        {            Console.WriteLine ("...");        }    }    Class American:ren    {public               override void Cry ()        {              Console.WriteLine ("Mygod,god bless me!");        }    }    Class Chinese:ren    {public        override void Cry ()        {            Console.WriteLine ("Goodness bless me! ");        }    }

In the main function, the first instance of a monster, randomly generated a Ren object, the reference of this object into the strange beast, through this reference to show a different state.

            Monster m = new Monster ();
Random rand = new Random (); int n = rand. Next (+); if (n% 2 = = 0) { American a = new American (); Or so write Ren a = new American (); M.eatfood (a); } else { Chinese c = new Chinese (); Or so write Ren C = new Chinese (); M.eatfood (c); }

C # Object-oriented niche learning (GO)

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.