C # Object Oriented (i)

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 capitalization   { int   age;  public  void  setage (int  a)  assign a value   {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:

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

classCircle {floatR;  PublicCirclefloata) {R=A; }         Public DoubleZhouchang () {return 2*3.14*R; }         Public DoubleMianji () {return 3.14* R *R; }    }    classProgram {Static voidMain (string[] args) {Circle M=NewCircleTen); Circle N=NewCircle -); DoubleBC =M.zhouchang (); DoubleMJ = (N.mianji ()-M.mianji ()); Console.WriteLine ("the perimeter of the inner circle is:"+BC); Console.WriteLine ("the area of the tiles 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.

1. Encapsulation

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 ()        {            " dragon God ";              - ;        }    }

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:

    classRen () {string_name; int_age;  PublicRen () {_name="ZSMJ"; _age= -; }             PublicRen (stringname) {_name=name; }             PublicRen (stringNameintAge ) {_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:

New Ren (" Wang ");

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   {      getreturn  _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:

     New Ren (" Wang ");      " 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 classMyDate {int_year; int_month; int_day; int_hours;  PublicMyDate (intYearintmonth) {_year=Year ; _month=month; }        PublicMyDate (intYearintMonthintDayintHours): 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;

 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:

   classFenbi {Static string_color;  Public Static stringColor {Get{returnFenbi._color;} Set{Fenbi._color =value;} }       int_lenght;  Public intLenght {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";       New Fenbi ();       ten;

(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.

     publicstaticvoid  Xiezi ()       {           Console.WriteLine (" Write  "+_color+ " the words ");       }
      Public void Change ()        {            Console.WriteLine (_color+" Chalk length changed to:"+_lenght);         }

10. Copy

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

C # Object Oriented (i)

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.