. NET basics and. net Basics

Source: Internet
Author: User

. NET basics and. net Basics
C # introduction to basic. NET

Computer Development History

First generation language: machine language 0101

Second-generation language: assembly language. It replaces the binary string of a specific instruction with some Concise English letters and symbols.

Third-generation language: similar to mathematical or human natural language, and independent of computer hardware, programmed programs can be used on all machines

Compilation and running process:

C # language-Public language specification (CLS)Compiler-MSIL (intermediate language or assembly)

-In the Common Language Runtime Library (CLR)Compiler-Operating System Code Execution

 

Purpose of the two compilation processes:

The first time is to compile different languages into intermediate languages to form an assembly;

The second time, We optimized the CLR for different operating systems.

 

Escape Character

Changed the original meaning of the character.

Quotation marks -- \ "" newline -- \ n horizontal tabulation -- \ t question mark --\?

Backslash -- \ add multiple backslash (escape prevention) -- @ "string"

 

Format a string

 

Variable

Where is the program running?

What is the program processing?

1. Definition

Memory space used to store data

It can store words, values, dates, and attributes.

2. Statement

Variable type variable name;

You can also declare multiple variables at a time. String str1, str2;

3. Naming rules

It may consist of letters, numbers, and underscores, and cannot begin with a number.

The reserved keyword (blue) cannot be used ).

4. Recommended naming rules

[Hope]

It must start with a lowercase letter.

If multiple words are included, we recommend that you use uppercase letters for the first word.

Adding a type prefix is easy to understand.

5. Variable assignment

A value must be assigned before use.

The data type of the value assignment must be the same as that of the variable declaration.

The same variable name can only be declared once, but can be assigned multiple times.

6. Data Types

 

1) Integer

 

2) Non-INTEGER (decimal)

Non-integer variables must be assigned with a suffix. If no value is added, the default value is double.

 

3) Non-numeric type

Char character, which stores a single character and uses single quotation marks.

For the Bool type, you can directly assign true to false, or assign an expression for determination.

7. placeholders

 

Operator

1. Arithmetic Operators

+-*/% + + --

I ++, ++ I

 

I ++, suffix incremental operation. The result of the expression is the value before the operand is added,Houjia: Post auto-increment.

++ I, prefix. The expression result is the value after the operand is added with 1,Add first: Auto-increment first.

2. Comparison Operators

><>==! =

3. logical operators

& -- A false combination is equivalent to "and ".

| -- Or is equivalent to "or", and one is true.

! -- Not true, not false

4. Shortcut Operators

+ =-= * =/= % =

 

Data Type Conversion

After the variable is declared, the type is fixed and only some type of value can be assigned. If you want to assign values of other types, you need to convert the type.

1. implicit conversion (Conversion between numeric types): conversion from a small range (Space) to a large range of numeric types. No failure, no loss of precision, generally occurring between numerical types.

2. Explicit conversions (forced conversions): (conversions between numeric types) there is a risk that the programmer decides not to convert. Precision may also be lost.

Syntax: New Type name = (to be converted type name) Name

 

 

 

By default,. NET does not detect force conversion errors. You can use the checked code block to detect force conversion errors.

3. parse (transfer out) converts strings to the corresponding type: the built-in data types all provide the parse method to convert strings and corresponding types.

Int a = int. Parse ("1 ");

Double d = double. Parse ("1 ");

4,ToString(Transfer) from other types to strings:

 

5, Convert conversion:Int i2 = Convert. ToInt32 ("9 ");

 

Constant

Unchanged content value

Use the const statement; for example:

We recommend that you name all uppercase letters to distinguish them.

 

Method

1. Definition: The method is to name a series of statements, indicating a behavior or function.

2. Role: code reuse for modular Development

3. Syntax

For example, Public and private static declarations: static/* returns a result value for a parameter */

 

 

Access level [Optional modifier] return type method name (parameter type parameter name)

{

// Method body

Return result;

}

No return value declared as void parameter list

4. Call Statement: Method Name (parameter)

5. Return Value: The result of the method.

Void indicates that no return value is returned.

If a return value exists in a method, a return statement must exist in the method body. If no return value exists, either of them can be used.

The Return keyword must Return data of the same type.

The statement after Return is no longer executed.

When calling a method, if a result is required, declare the corresponding type of variable to receive the returned data.

6. Parameter List: information that the method designer needs to pass by the caller

This parameter is used to define a method.

The call method is called a real parameter.

The input parameters must correspond to each other.

The principle of determining parameters: data that you can determine is resolved internally, and data that you cannot determine is transmitted through parameters.

7. The method is as small as possible to complete an independent task.

8. You can call methods in the same class or other classes. You can also call other methods internally.

 

Parameters

1. Value Parameters

The method is passed by default, and a copy of the variable is passed.

When a value type parameter is passed to a method, it transmits a copy of the data instead of the data itself.

The modification of form parameters inside the method does not affect the actual parameters outside the method.

 

2. Reference parameters

When an object of the reference type is passed to a method, a variable of the reference type does not directly contain its data; it contains a reference (Address) to its data ), that is, the reference points to the original object rather than the copy. Ref is a keyword.

Parameters modified in the method will affect the actual parameters.

It is used to modify an existing variable in the method, and is more focused on changing one.

 

/* If the ref parameter is added, the two parameters are the same. */

3. Output Parameters

The Out keyword causes the parameter to be passed through reference. This is similar to the ref keyword. To use the out parameter, the out keyword must be used for method definition and call.

Focuses on outputting a value.

4. Differences

Ref requires that the variables must be initialized before being passed (with initial values ). Variables passed as the out parameter do not need to be initialized before being passed, but they must be assigned a value before leaving the method.

5. Purpose

To return multiple values.

TryParse

Use Bool expressions with TryParse to prevent type conversion failure.

Syntax: TryParse (string to be converted, variable name to be transferred out)

 

Method overload

Method signature: the access level, optional modifier, return value, name, and any method parameters of the method, collectively referred to as the "signature" of the method ".

Method OverLoad: In the same scope, the two methods have the same name. The parameter list (number and type) is different from the method OverLoad ). Used to solve the same type of problems. [The Difference Between out and ref cannot be composed]

Purpose: reduce the memory volume for ease of use and ease of understanding

Select statement If statement

If (bool expression)

{

// If the expression is true, run

}

Else

{

// The expression is false.

}

C # specifies that each else part is always the if statement of the last one that lacks the corresponding else part.

Note: Else is optional;

A single-line statement can be left blank {}, but a single-line statement must also be written;

If conditions cannot be followed by extra points;

 

 

 

 

 

 

Switch-case statement

Multi-path judgment statement

Calculate the conditional expression and check against multiple constant values

1. Note

Break cannot be less

The variables in Switch () can be int, string, bool, char, or enumeration type,

But there must be a value.

Each case tag is followed by a constant expression value, which does not need to be continuous or specified

Ordered, but not the same. Otherwise, an error occurs.

The number of statements after each case tag is unlimited. If you have multiple statements, you do not need to use {}.

The default tag is optional. Other results.

2. Differences

Similarities: both can be used to achieve multiple branches.

Differences

The multi-if structure is convenient to implement two-way and three-way branches, and the Switch structure is convenient to implement more than three-way branches.

The If structure is used to determine whether a value is in a certain range. When a switch is used, the case statement must be followed by a constant expression.

Loop statement For statement

The execution cycle must be allowed only after the characteristic conditions are determined. It is used to repeatedly execute a specified number of statements or statement blocks.

For (initial value; condition; variable increase/decrease)

{

............ Z

}

First, assign the initial value and execute it only once.

Determine whether the condition expression is met. If the statement in {} is executed, if not, exit the loop.

After each statement in the loop is executed, the variable is increased or decreased.

Break is used to exit the loop.

Continue is used to jump out of the current loop and start the next loop of this.

There can be an endless loop (;;)

Example:

 

 

 

 

While statement

While (condition true)

{

// Exit condition

// Statement

}

Execute a statement or statement block until the specified expression is calculated as false to exit the loop.

First, determine whether the expression meets the conditions. Yes: Execute the statement; no, exit.

In most cases, while statements can be exchanged with for statements, while statements are often used to calculate an uncertain number of times.

 

Do While statement

Do

{

// Loop body

}

While (condition)

Execute statements in {} repeatedly until the specified expression is false.

Difference from while: the loop body must be executed at least once.

Loop nesting

 

Example: Positive triangle

 

Example: inverted triangle positive triangle:

 

 

 

 

 

 

 

 

 

 

 

Example: multiplication table

 

Array

Definition: stores a group of variables of the same type. It is a spatial continuous data structure.

These variables can be accessed through the calculation index (location.

Array attributes

The index of the array starts from scratch, and the index of the array with n elements (variables) ranges from 0 to n-1 (because it starts from 0 ).

Array elements can be of any type, including array types (array nesting ).

The Array type is a reference type derived from the abstract base type Array.

You can use foreach to traverse all arrays in c.

Array type

One-dimensional array

Multi-dimensional array (with rows and columns or high)

Staggered Array

Syntax for declaring a value Array

 

 

 

 

 

 

 

● An array must be assigned a value before it can be used.

● Access the array and traverse it cyclically through indexes using for and foreach.

● The For loop can read and set element values without accessing all elements.

● Loop traversal: foreach and

Foreach loop. You cannot assign values to elements and traverse the elements in sequence. You cannot skip or retrieve indexes.

 

Common array methods and attributes

1. Length

Returns a 32-bit integer that represents the total value of elements in all dimensions of the Array.

Syntax: array name. Length

 

2. Rank dimension

Returns the dimension of an Array.

Syntax: array name. Rank

 

 

 

3. Clear element values by Array. Clear ()

Set the element in the array to 0, null, or fasle, depending on the data type of the array element.

Syntax: Array. Clear (name of the cleared coordinate Array, starting coordinate, ending coordinate)

 

 

4. copy Array. copy

Copy part of an array to another array, and copy an element of a certain length from index 0.

Syntax: Array. Copy (name of the copied Array, name of the copied Array, number of elements );

 

 

5. CopyTo Replication

Copy the element content of the source array to the target array, starting from an index of the target array and ending the replication. The length of the target array must be greater than or equal to the length of the source array.

Syntax: source array name. CopyTo (target array name, element location where the target array begins to copy)

Note: The length of the target array must be greater than that of the source array;

Replace the target array element from the starting element. The content of the target array greater than the source array is retained.

 

6. Clone

Cloning copies the known array to the newly defined array, so you need to declare the new array for receiving;

Forced conversion is required for cloning: (array type [])

Syntax: newly defined array = (array type []) target array name. Clone ();

 

 

7. Array. IndexOf () looks forward to the index (element location) of the First matching item)

Array. LastIndexOf () reverse searches for the index of the first matching item

Returns a value in an array or partial array.FirstThe index of the matched item.-1 is returned if no matching item is found.

Syntax: Array. IndexOf (Array name, element)

 

 

8. Array. Sort () sorting

Syntax: Array. Sort (Array name)

 

 

9. Array. Reverse () inversion

Reverse the order of elements in the array

Syntax: Array. Reverse (name of the Array to be reversed)

 

 

 

Exercise: Bubble Sorting

Comparison between the two, big put to the back

2 8 6 1

First round:

2 6 1 8 Comparison 3 times 4-1

Round 2:

2 1 6 8 Comparison 2 times 4-2

Round 3:

1 2 6 8 Comparison 1 time 4-3

 

4. Number comparison

4-1 round

Per wheel: Total number of elements-current wheel count (I + 1)

 

Two-dimensional array

● A two-dimensional array is like a table with rows and columns.

● A two-dimensional array has two indexes, representing rows (Front) and columns (back) respectively ).

● Int [,] score = new int [5, 2];

Declare initialization value assignment

 

Read assignment

Name [row, column]

Attribute

 

 

Exercise: five students take the test of two courses, and calculate the average score of each student and the average score of two courses.

 

Staggered Array

● An interleaved array is an array of elements (nested arrays ).

● The size of elements in the staggered array can be different (elements are arrays, indicating that the size of arrays in the staggered array can be different ).

● Declare a one-dimensional array composed of five elements. Each element is a one-dimensional integer array.

● Int [] [] score = new int [5] [] 5 is the peripheral array (ROW) [] as the internal Array

 

Exercise: Enter the number of students, number of exam subjects, and corresponding scores

 

Params parameter Array

● Define the parameter Array Using the keyword params

● It is used when the method parameters are not fixed.

● You can pass arrays or multiple variables of the same type.

Function

● Declare functions when the array length is unknown (variable.

Note:

● Unlimited quantity.

● The parameter array must be the last parameter in the method declaration.

● A method can have only one parameter array.

● The params keyword can only be used on one-dimensional arrays.

● Using placeholders in Console. WriteLine is implemented using parameter arrays.

Data Type Value Type

● Store values directly. (Data is stored in the stack)

● When a value type variable is assigned to another value type variable, a data copy is copied to it (two data are generated in the stack ).

●Changing the value type does not affect other values.. (Because it is two pieces of data, they do not affect each other)

 

Reference Type

● Store the reference address of the data. (The variable is defined in the stack, while the data is actually stored in the heap, and the data is only referenced to the variable)

● When assigning values, only the reference address of the object is copied, instead of the object itself. (The actual data is only one copy)

● Two variables of the reference type can point to the same object.

●Changing a variable of the reference type may affect other objects.. (Because it is a copy of data)

Type attribution

● Value Type: enumeration, structure (basic type)

● Reference type: Class (including array, string), interface, delegate

String type

● String is a special reference type. (Because the reference type exists in the heap and a large amount of content can be stored, the string is defined as the reference type)

●String constantYesString pool features(Concatenate string variables to form a new object)

● After the String value is assigned again (s1 = ""), the value of s1 is not affected. However, the original data is junk.

● Value after String assignment, yesUnchangeable).

● Variable character string: stringBuilder.

Modify the stringBuilder on the original string, and replace the string with the new one.

 

 

 

 

Cause

The memory stack can store small data and run fast. The stack can store large space but run slowly. So the value type is on the stack, and the reference type is on the heap.

 

Declare and release reference type variables

Use the null keyword to release data (assign a null String ).

 

 

After the spam is released, it will be automatically recycled.

 

Comparison Value Type

In doing = and! = When compared, compare the stored values (real data ).

 

Comparison reference type

Doing = and! = During the comparison, the referenced position is not the same, rather than the referenced value.

 

Enumeration type

● Definition: lists all values of a data.

● Function: enhances code readability and limits the value.

● Applicability: The value range is small.

● Use the enum keyword to define the enumerated data type.

● Syntax: enum name {value 1, value 2, value 3, value 4}

● Each enumeration element has an enumeration value. By default, the value of the first enumeration is 0, and the value of each enumeration increases by 1 at a time. You can modify the value and the value of the subsequent enumeration increases at a time.

● The basic type of enumeration elements is int by default. The supported enumeration types include byte, sbyte, short, ushort, int, uint, long, And ulong.

● Type conversion

// String type conversion to Enumeration

Sex s1 = (Sex) Enum. Parse (typeof (Sex), "male ");

// Convert enumeration to string

String str = Sex. Female. ToString ();

 

// Int type conversion to Enumeration

Sex s2 = (Sex) 3;

// Convert the enumerated type to the int type

Int I = (int) Sex. Male;

● Flag Enumeration

Multiple enumerated values can be assigned at the same time.

[Flags] // flag Enumeration

Enum Sex

{

Male = 1, // 000001

Female = 2, // 000010

Unknown = 4 // 000100

}

Sex s3 = Sex. Male | Sex. Female;

// System. Drawing. FontStyle

● Determine whether the flag enumeration value contains a certain value

Bool B = (s2 & Sex. Male) = Sex. Male;

// 00011

// 00001

// 00001

 

String operation attributes

● Use the s. Length attribute to obtain the number of characters in the string.

● The content of a string is immutable once declared. Therefore, it can only be read and cannot be modified.

● If you want to modify the string content, create a new string using s. the ToArray () method gets the char array of the string. After modifying the array, call the new string (char []) constructor to create the string of the char array. Once a string is created, the modification of the char array will not change the string.

 

● StringBuilder variable string.

 

 

Common String functions

● Insert the character. Insert () into the string ();

 

 

● If this character exists in the search string, return the bool value.

 

 

● ToLower (); returns the string in lowercase.

Or

 

● ToUpper (); returns the string in uppercase format.

 

 

● Search for the string location

 

 

● Obtain substrings

 

 

● Trim (); Removes spaces at both ends of the string. Used to avoid incorrect user input.

 

 

● Two strings (si and s2) are case-insensitive.

 

 

● Split the string into character arrays based on the specified char separator and splice them

 

 

 

 

● Split the string into character arrays based on the specified char separator and ignore null characters

 

 

● Replace the individual content in the string.

 

● Obtain substrings

 

Exercise:

1. String inversion: "I want to learn"

String str = "I want to learn ";

Char [] toChar = str. ToArray ();

Array. Reverse (toChar );

String toStrint = new string (toChar );

Console. WriteLine (toStrint );

 

2. Word inversion: I want to learn

String str = "I want to learning ";

String [] toArry = str. Split ('');

Array. Reverse (toArry );

String toString = string. Join ("", toArry );

Console. WriteLine (toString );

 

 

Uppercase and even characters:

String str = "I want to learning ";

String result = string. Empty;

Char temp = '\ 0 ';

For (int I = 0; I <str. Length; I ++)

{

If (I % 2 = 0)

{

Temp = char. ToUpper (str [I]);

}

Else

{

Temp = char. ToLower (str [I]);

}

Result + = temp;

}

Console. WriteLine (result );

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.