15-01-11 C # Object-oriented 10

Source: Internet
Author: User

The member in the class, if not the access modifier, is private by default;

Private, accessible only within the current class;

In theory, each private field is provided with a public attribute;

Only static members can be accessed in static functions, static members can only be static, non-static functions have access to both static and non-static members, and non-static classes can have static members or non-static members;

The purpose of this 1. The object of the current class is to distinguish between a field (attribute) and a local variable, and a field and a property as a method, while a local variable is inside a method;

Namespace (namespace), used to solve the class name problem, can be regarded as the folder of classes;

There are many classes in namespaces, and namespaces are actually equivalent to projects;

If we are going to use a new class, but this new class does not exist in the namespace above, we will first refer to the namespace of this class;

Class is a namespace (project), we cannot use this class without referencing the appropriate namespace.

How to reference the namespace of a class,

1. Put the cursor under the name of the class, you will see a small blue block in the lower left corner, the cursor moved over the point, you can refer to the namespace

2. Place the cursor under the name of the class, ALT+SHIFT+F10;

3. Remember the namespace and hit it directly on it;

If in your own two projects, I would like to reference 01 projects in 02 projects,

The first step, add the reference, in the 02 project file reference, right-click, add Reference, the default is the project, select the referenced project, click OK, this time found in the 02 project references have 01 projects; (The system comes with less of this step)

The second step, referring to the namespace above,

The exact type of data in C # is divided into value types and reference types, which differ by 1. Value types and reference types, which are not stored in memory, 2. When passing value types and passing reference types, they are passed differently, value types we call value passing, reference types we call reference passing

In memory we have scored 5 dollars, our programmers commonly used is heap, stack, static storage area, static storage area to store static members, stack is used to store our data types of data

Value type: Int,double,bool,char,decimal,struct,enum

Reference type: string, custom class, array

Values of value types are stored on the stack in memory, and the value of the reference type is stored in the heap of memory.

int number = 10; 10 exists in the stack, the name of the stack memory space is number

string s = "123"; "123" exists in the heap, S is in the stack, but the stack space with the name S is the address of "123" in the heap;

Person p = new person (); P.name = "Zhang San"; New person () exists in the heap, the new person () is an object, p is in the stack, but the stack space with the name P is the address of the new person () in the heap; Name = "Zhang San" is also in the heap

The value of a value type is present in the in-memory stack, the value of the reference type exists in the in-memory heap, but the reference type also opens up space on the stack, which is the reference (address) of the value in the heap;

Strings differ from other types having a very special nature, called

1. Immutability of the string, int n1 = 10;    NI = 20; 10 in the heap becomes 20; the old value is 10, it does not exist; string S1 = "Zhang San"; S1 = "John Doe"; When you re-assign the string, the old value "Zhang San" is not destroyed, but re-open a heap of space to store the new value, the S1 in the stack address from the original "Zhang San" address into the "John Doe" address, when Zhang San in memory and therefore the string loop assignment, it will generate a lot of garbage in the heap memory; When the program is finished, the GC scans the entire memory, and if it finds that some space is not pointed, destroy it immediately;

string S1 = "Zhang San";    String s2 = "Zhang San"; Theoretically there are 2 blocks of space in the heap to store "Zhang San", in the stack there are two space s1,s2 respectively point to their respective "Zhang San"; but it is not, in fact, only a space in the heap, called "Zhang San", S1,s2 also point to Zhang San; s1,s2 address in the heap is the same, at this time s1= "123" The original "Zhang San" is immutable, because the string is immutable, so it will be in the heap space to re-open a space to store "123";

How to look at the variable in memory address, build run, Debug menu, window, instant inside, in the Immediate window input & variable name, enter can be seen; there are two addresses, the above is the address in the stack, the following is the address in the heap

2. We can consider a string as a read-only group of type char; A string type can be seen as a number of many char types, many of which can be considered an array;

Read-only meaning can only be accessed, but can not be changed;

string s = "ABCDEFG"; since s can be treated as an array, it means that an index can be used to access one of the elements;  Console.WriteLine (S[0]); Successful output A

If you want to change the first character A to B, first try to find a way to access the first character; S[0] = ' B ';//error because string is a read-only group of type char;

If you want to change the first character of a string to ' B ';

1. First convert the string to an array of type char, convert it to a real array, then both readable and writable;

char[] CHS = S.tochararray (); Chs[0] = ' B ';

2. Convert the character array to a string;

s = new string (CHS);

ToCharArray () Converts a string into a char[] array; New String (char[] CHS) can convert char[] to a string;

When the program to a large number of re-assignment of strings, splicing and other operations, if the use of string, in the heap memory will generate a lot of garbage so we can use StringBuilder this class;

StringBuilder sb = new StringBuilder ();

Record the time that the program runs, we can use stopwatch this class;

StopWatch SW = new StopWatch ();//Create a timer;

Sw.  Start (); Start timing;

Sw. Stop (); End timing;

Sw. Elapsed the time taken to obtain the measurement;

str + = i; string append; Sb. Append (i); append;

Why does the string append so slowly, because it has to open up space in memory each time; StringBuilder has no space; Although StringBuilder is used in the middle, it is finally converted to string, SB. ToString ();

All types can be converted to string types by ToString ();

Str.  Length; Invokes the string's properties to get the length of the string;

Str.  ToUpper (); Converts a string into uppercase;

Str.  ToLower (); Converts a string into lowercase;

Str. Equals (str1,stringcomparison.ordnialignorecase); Comparison of two strings ignoring case;

Char[] CHS = {' _ ', ' + ', '-', ' * ', '};

Str.split (chs,stringsplitoptions.removeemptyentries); in Str, the characters in the array are removed, the return value is string[];

Two small yellow blocks are enumerated types

Str.split (New char[]{' _ ', ' + ', '-', ' * ', '},stringsplitoptions.removeemptyentries '); equivalent to;

Str. Contains ("Lao Zhao"); Judging whether there is an old Zhao in the string;

Str. Replace ("Lao Zhao", "* *"); Replace the old Zhao in the string with the * *;

Substring and split often use these two methods in strings; Str. (Substring); 1 is the index to intercept the start, 2 is the length to intercept;

Str. StartsWith ("Today"); judging whether the string starts with "Today";

Str. EndsWith ("Today"); Judge whether the string ends with "Today";

Str. IndexOf (' Day '); Gets the index of the first occurrence of the ' Day ' in the string, and the return value int; If not found, return-1;

Str. IndexOf (' Day ', 2);  The index from which the second index starts looking for the first occurrence of the day, and the return value int; If not found, return-1;

Str. LastIndexOf (' Day '); Find the index of the last occurrence of the day in the string;

string path = @ "c:\a\b\c........\. wav";

int idndex = path. LastIndexOf ("\ \");

Path = path.  SubString (index+1); Gets the file name;

Str. Trim ();//Remove the front and back spaces of the string

Str. TrimStart ();//Remove the spaces in front of the string

Str. TrimEnd ();//Remove the space after the string

String. IsNullOrEmpty (str); Determines whether a string is null or null;

string[] Str ={"Zhang San", "John Doe", "Harry", "Zhao Liu", "Tianqi"};

String strnew = String.Join ("|", str); Get Zhang San | John Doe | harry | Zhao LIU | tianqi

String strnew = String.Join ("|", "Zhang San", "John Doe", "Harry", "Zhao Liu", "Tianqi"), or it can be written because the params variable parameter is preceded;

When a string is run (assigned, spliced), a new instance is created, and StringBuilder does not produce a new instance.

The file class is a static class;

File.ReadAllLines (Path,encoding.default)

Path is the directory of the file, and all rows in the file are read, and the return type is string[]; Encoding.default used to solve garbled characters;

To change a string, in addition to the re-assignment, you can turn it into an array of characters, in the loop or call method to change the character array, and then convert the character array into a string;

The string method provided by the. NET class library is still very powerful;

Encapsulation is the ability to write a function as a method call, and how this function is implemented does not have to be known, just as the method provided by the. NET class library is called.

Each write a class should create a new class file to write;

public class Student:person

{

private int _id;

public int Id

{

Get{return _id;}

set{_id = value;}

}

public void Study ()

{

Console.WriteLine ("Learning");

}

Public Student (string name, int Age,char gender,int ID)

//{

This. name = name;

This. Age = age;

This. Gender = Gender;

This. id = ID;

//  }

Most of the code has already been written in the parent class, and if one row is not saved by using the parent's parameterless constructor, the constructor that calls the parent class has a parameter

As a result, the constructor executes, the object is created, and three lines of code do not need to be written.

Public Student (string name, int age,char gender,int ID)//Run to this point, jump to the constructor of the parent class;

: Base (Name,age,gender)

{

This. id = ID;

}

Public new void Test ()

{

Console.WriteLine ("Test 1");

}

}

public class Teacher:person

{

Public Teacher (String name,ing age,char gender,int salary): Base (Name,age,gender)

{

This. Salary =salary;

}

private int _salary;

public int Salary

{

Get{return _salary;}

Set{_salary = value;}

}

public void Teach ()

{

Console.WriteLine ("Teaching");

}

Public new void Test ()

{

Console.WriteLine ("Test 2");

}

}

public class Driver:person

{

private string _drivetime;

public string Drivetime

{

Get{return _drivetime;}

Set{_drivetime = value;}

}

public void Drive ()

{

Console.WriteLine ("Drive");

}

Public Driver (String name,ing age,char gender,int drivetime)

: Base (Name,age,gender)

{

This. Drivetime =drivetime;

}

Public new void Test ()

{

Console.WriteLine ("Test 3");

}

}

constructor can solve the code redundancy at the time of object initialization,

: This can solve the redundant code when the constructor overloads;

Inheritance is used to solve the code redundancy between classes and classes, and to separate the members of several classes into a single class as the parent class of these classes;

public class Person

{

private string _name;

public string Name

{

Get{return _name;}

Set{_name = value;}

}

private int _age;

public int Age

{

Get{return _age;}

Set{__age = value;}

}

private string _gender;

public string Gender

{

Get{return _gender;}

Set{_gender = value;}

}

public void Chlss ()

{

Console.WriteLine ("Eat and Drink and sleep");

}

Public person (string Name,int Age,char gender)

{

This. name = name;

This. Age = age;

This. Gender = Gender;

}

Public person ()

// {

//   }

public void Test ()

{

Console.WriteLine ("Test");

}

}

The cube of intelligent hints is the meaning of the method;

A subclass can be either a member of the parent class or a member of its own;

We may write some duplicate members in some classes, and we can encapsulate some duplicate members, individually, into a class, as the parent class of these classes.

Student,teacher,drive subclass (derived class)

Person Parent class (base class)

We see what the subclass inherits from the parent class, just what the subclass object can access to the parent class, and the representation that can be accessed to inherit it.

In the above example, the subclass inherits the properties and methods of the parent class, and the subclass does not inherit the private field of the parent class;

1. Inheritance of the single root, a subclass can have only one parent class;

2. The transitive nature of inheritance, a inherits B,b inherits C A can not only access the members of B, a can also access the members of C;

View class diagram: You can see the relationship of each class, right-click the project name, view, view the class diagram;

If the subclass inherits the constructor of the parent class, then the constructor of the parent class should be called when the subclass object is created;

Subclasses do not inherit the constructor of the parent class, but when the subclass creates the object, it executes the constructor of the parent class, executes the constructor of the parent class, executes its own constructor, and executes the constructor of the parent class to create a parent class object.

When we create a subclass object, we first create an object of the parent class inside the subclass so that the properties and methods of the parent class are used, otherwise there is no object of the parent class in the subclass object, how to invoke the property and method of the parent class;

Therefore, after the parent class has written a constructor that has a parameter, the constructor of the parent class is eliminated, and the object of the parent class cannot be created (because the child class creates the object, it calls the parent class without the parameter constructor); If a parameter constructor is re-written in the parent class, the non-argument is killed and the subclass is not called, so the subclass will error,

Solutions

1. Re-write a parameterless constructor in the parent class; Generally not to do so;

2. Display the constructor of the calling parent class in the subclass, keyword: base ()

Ctrl+k+d code alignment;

Originally the subclass call is the parent class parameterless constructor, now write a parameter of the parent class constructor, the original non-parameter of the parent class constructor was killed, so cannot tune to the original parameterless constructor, so go to call the constructor of the argument, using the keyword: base ();

Student s = new Student ("student", 18, ' Male ', 101);

The object class is the base class for all classes; If you do not allow a class to inherit another class, the class inherits from object by default;

All classes in C # Inherit the object class directly or indirectly;

If the member name of the child class is the same as the member name of the parent class, the members of the same name inherited from the parent class are hidden;

Public new void Test () hides members of the same name in the parent class, and adds new without warning errors;

New 1. Create object 2. Hide members with the same name inherited from the parent class

Hidden consequences, subclasses are not called to the hidden members of the parent class;

Therefore, when inheriting, try not to write the names of the members of the class and the names of the members of the parent class;

Object is also a reference type, because it is a class;

15-01-11 C # Object-oriented 10

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.