. NET Foundation Chuanjiang

Source: Internet
Author: User
Tags arithmetic operators case statement ranges rounds true true

C # Foundation. NET Introduction

? Computer History

First generation language: Machine language 0101

Second-generation languages: assembly language, replacing a binary string of a specific instruction with some simple English letters and symbolic strings

Third-generation language: close to the mathematical language or human natural language, while not relying on computer hardware, the programmed program can be used on all machines common

? Compile the Run process:

C # language- compiler -msil (intermediate language or assembly) for the Common Language Specification (CLS)

- Compiler -operating system execution code in the common language runtime (CLR)

? Two compile process uses:

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

The second time for the CLR to be optimized for different operating systems.

Escape character

Changed the original meaning of the character.

Quotation marks--\ "" Line--\n horizontal tab--\t question mark--\?

Backslash--\\ plus multiple backslashes (prevents escaping)--@ "string"

formatting strings

Variable

Where is the program running?

What is the program dealing with?

1. Definition

? A piece of space in memory for storing data

? You can store words, values, dates, and attributes.

2. Statement

? Variable type variable name;

? You can also declare multiple variables at once. String str1, str2;

3. Naming rules

? There are letters, numbers, and underscores, and you cannot start with a number.

? You cannot use the reserved keyword (blue).

4. Recommended naming rules

Words too literally

? start with a lowercase letter.

? If more than one word is included, it is recommended to capitalize the first letter of the word other than the first word.

? Adding type prefixes is easy to understand.

5. Assigning values to variables

? You must assign a value before using it.

The type of the assigned data type and the variable declaration must be the same

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

6. Data type

1) Plastic Surgery

2) Non-integral type (fractional)

? Non-shaping variable assignment to add a suffix, if not the default is double

3) Non-numeric

? Char character, which stores a single character, using single quotation marks.

? The bool type can be directly assigned true true false, or an expression to be evaluated.

7. Placeholder

Operator

1. Arithmetic operators

+-*/% + +--

? i++, ++i

i++, Postfix increment operation. The result of the expression is the value before the operand is incremented , followed by the increment: after.

++i, prefix. The result of the expression is the value after the operand plus 1, plus : increment first.

2. Comparison operators

? > < >= <= = = =!

3. Logical operators

The &&--and the fake are the equivalent of "and" all must be true

?|| --or one that's really the equivalent of "or" one of them is real.

?! --Not original is true, non-false after

4. Shortcut operators

+= -= *= /= %=

Data type conversions

After a variable is declared, the type is fixed, only a numeric value of a certain type can be assigned, and if a value of another type is to be assigned, a conversion type is required.

1. Implicit conversions (conversions between numeric types): Conversion of numeric types from small ranges (spaces) to large ranges. No failure, no loss of precision, typically occurs between numeric types.

2. Explicit conversion (CAST): (conversion between numeric types) there is a risk, and the programmer decides to be non-convertible. Accuracy may also be lost.

Syntax: new type name = (to go to type name) name

. NET does not detect cast errors by default, and a checked code block can be used to detect cast errors.

3. Parse (turn out) converts the string to the corresponding type: The built-in data types provide a parse method that implements the conversion of strings and corresponding types.

int A=int. Parse ("1");

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

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

5 , convert convert: conversion between any two types int i2 = Convert.ToInt32 ("9");

Constant

? values that do not change content

? Use the const declaration, such as:

? It is recommended to name all uppercase to differentiate

Method

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

2, the role: code reuse, to achieve modular development

3. Grammar

such as public, private declaration static: statics/* 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: interpreted as the result of the method

void represents no return value.

? If the method has a return value, the method body must have a return statement; There is no return value.

? The return keyword must return the same type of data.

? The statement after return is no longer executed.

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

6. Parameter list: The method designer needs the information passed by the caller

? Define method called formal parameter

The calling method is called an argument.

The actual participation parameters should be corresponding

The principle of determining parameters: self-determination of the data themselves internally resolved, the data can not be determined by the parameters passed.

7, the method as small as possible in order to complete an independent work.

8, you can call methods in the same class or other classes, or you can call other methods internally.

Parameters

1. Value parameter

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

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

? method internal modification of formal parameters does not affect the actual parameters outside the method.

2. Reference parameters

When passing an object of a reference type 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 instead of the copy. Ref is a keyword.

How to modify the formal parameters in the method will affect the actual parameters.

? used when modifying an existing variable outside the method, focusing more on changing one.

/* Added ref, two parameters are the same. */

3. Output parameters

? The Out keyword causes parameters to be passed by reference. This is similar to the REF keyword. To use out parameters, both the method definition and the calling method must use the Out keyword.

? Focus on outputting a value.

4. Difference

Ref requires that a variable be initialized before it is passed (the initial value is assigned). A variable passed as an out parameter does not have to be initialized before it is passed, but the variable must be assigned a value before leaving the method, and there is an assignment operation.

5. Use

The method needs to return multiple values when used.

TryParse

? Use with TryParse with bool expressions to prevent type conversions from failing.

? Syntax: TryParse (string to be transferred, out-of-turn variable name)

Method overloading

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

? Method overloading: In the same scope, two methods have the same name, and the parameter list (number, type) is different, called Method overloading (overload). Used to solve the same type of problem. [The difference between out and ref can not be constituted]

Function: Reduce memory, easy to use, easy to understand

SELECT statement If statement

If (bool expression)

{

Expression is true, execution

}

Else

{

Expression is pseudo-executed

}

? C # stipulates that each else part is always the nearest if statement that lacks the corresponding else part.

? Note: Else optional;

One-line statement can not write {}, but the promotion of a single line should also be written;

If condition cannot add semicolon;

Switch-case statements

? Multi-Channel judgment statement

? evaluates a conditional expression and checks against multiple constant values

1. Attention

? No less break

? The variables in Switch () can be int, string, bool, char, enum type,

But there must be a fixed value.

? Each case label is followed by a constant expression that does not have to be contiguous and does not have to be specified

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

? The number of statements after each case label is unlimited, there are multiple statements, and you can do without {}.

? The default tag is optional. It means the rest of the results.

2. Difference

? The same point: all can be used to implement a multi-branch.

? Different points

The multi-if structure is convenient for two-way and three-way branches, and the switch structure is more convenient to realize the three-way branches.

If the structure is used to determine whether a value is in a certain interval, the case statement must be followed by a constant expression when using switch

Loop statement for statement

A loop is allowed to be executed only after the feature condition has been judged to repeat a predetermined number of times for a statement or block of statements.

for (initial value; condition; increment or decrement variable)

{

....... z

}

? First assign the initial value and execute only once.

Determines whether the conditional expression is satisfied, if it is executed within {}, if not, exits the loop.

Each time you execute a statement inside the loop, you execute the increment or decrement variable.

? break to Exit a loop

The continue is used to jump out of the current loop and start the next loop for this for.

? can have a dead loop for (;;)

Example:

While statement

while (conditional true)

{

Exit Criteria

Statement

}

Executes a statement or block of statements until the specified expression evaluates to False to exit the loop.

? First to determine whether the expression satisfies the condition, yes, executes the statement; no, exits.

? In most cases, the while statement can be interchanged with the for statement, while the common term is indeterminate.

Do While statement

Do

{

Loop body

}

while (condition)

Execute the statement inside {} repeatedly until the specified expression is false to exit.

? differs from while: the loop body is executed at least once.

Loop nesting

Example: Positive triangle

Example: Inverted triangle positive triangle:

Example: Multiplication table

Array

Definition: Storing a set of variables of the same type, is a spatial continuous data structure.

? These variables can be accessed by calculating the index (location).

Array properties

The index of an array is zero-based and the index of an array with n elements (variables) is indexed from 0 to n-1 (since 0).

An array element can make any type, including array type (array nesting).

? The array type is a reference type derived from the abstract base type array.

? You can use a foreach traversal for all arrays in C #.

Array type

One-dimensional arrays

multidimensional arrays (with rows and columns or heights)

Jagged arrays

Syntax for declaring an array of assignments

Array declarations must be assigned before they can be used.

Accesses an array, through an index, using a for, foreach Loop traversal.

The For loop can read, set element values, and do not have to access all elements.

Loop traversal method: foreach and for

The Foreach loop, which cannot be assigned a value, iterates sequentially, cannot jump, and cannot get an index.

Common methods and properties of arrays

1, length

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

Syntax: array name. Length

2. Rank Dimension

Gets the number of dimensions of the array.

Syntax: array name. Rank

3, Array.clear () clear element value

Sets the elements in the array to 0, NULL, or Fasle, depending on the data type of the array element.

Syntax: array.clear (cleared coordinate array name, starting coordinates, end coordinates)

4, Array.copy copy

Copies part of an array of elements into another array, starting at index 0 to copy elements of a certain length.

Syntax: Array.copy (the copied array name, the array name copied to, the number of elements);

5, CopyTo copy

Copies the contents of the source array element to the destination array, starting at an index of the target array and ending the copy, the destination array must be greater than or equal to the source array length.

Syntax: source array name. CopyTo (target array name, target array starting copy of element position)

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

Replaces the target array element from the set starting element, and the target array is larger than the contents of the source array are preserved

6. Clone cloning

Cloning is to copy the known quantity group to the newly defined array, so it is necessary to declare a new array for reception;

Clones must be cast, i.e.: (array type [])

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

7, Array.indexof () to find the index of the first match (element position)

Array.lastindexof () reverse lookup of the first occurrence of an index

Returns the index of the first occurrence of a value in a pair of arrays or parts of an array, and no return-1 is found.

Syntax: Array.indexof (array name, Element)

8, Array.Sort () sort

Syntax: Array.Sort (array name)

9, Array.reverse () reversal

Reverses the order of elements in an array

Syntax: Array.reverse (the name of the array that needs to be reversed)

Exercise: Bubble Sort

22 comparison, large put to the rear

2 8 6 1

First round:

2 6 1 8 comparison 3 times 4-1

Second round:

2 1 6 8 comparison 2 times 4-2

Third round:

1 2 6 8 comparison 1 times 4-3

4 Number Comparison

4-1 Rounds

Each round: Total number of elements-current number of rounds (i+1)

Two-dimensional arrays

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

A two-dimensional array has two indexes, representing rows (front), columns (later), respectively.

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

Declaring initialization assignment

Read Assignment

name [row, column]

Property

Exercise: 5 students took the 2-course exam and counted the average score of each student and 2 subjects.

Jagged arrays

A jagged array is an array of elements (nesting of arrays).

The size of a jagged array element can be different (an element is an array, which means that the array size in a jagged array can be different).

Declares a one-dimensional array of 5 elements, each of which is a one-dimensional array of integers.

Int[][] Score =new Int [5][] 5 is a perimeter array (row) [] is an intrinsic array

Practice: Enter the number of students, test subjects, and corresponding results

Params parameter array

Defining a parameter array from the keyword params

For applications where the method parameters are not fixed

You can pass an array, or you can pass multiple variables of the same type.

Role

A function declaration is made when the length of an array is unknown (mutable).

Attention

Unlimited quantity.

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

Method can have at most one parameter array.

You can use the params keyword only on one-dimensional arrays.

The use of placeholders in Console.WriteLine is implemented using parameter arrays.

Data Type value type

Store values directly. (Data stored in the stack)

When a value-type variable is assigned to another value-type variable, a copy of the data is copied to it (generating 2 data in the stack).

changing the value type does not affect other values. (because it is 2 data, it does not affect each other)

Reference type

Stores a reference address to the data. (the variable is defined in the stack, and the data is actually stored in the heap, and the data is simply referenced to the variable)

Assigning a value only copies the reference address of the object, not the object itself. (Only one copy of the actual data)

A variable of two reference types can point to the same object.

changing a variable of a reference type may affect other objects . (because it's a piece of data)

Type attribution

Value types: enumerations, structs (underlying types)

Reference types: classes (including arrays, strings), interfaces, delegates

String type

String is a special type of reference. (because a reference type exists in the heap, you can save a lot of content, so string is defined as a reference type)

String constants have string pool attributes ( string variables are spliced to form new objects )

After the string is re-assigned (s1= "ER Mao"), the value of S1 is not affected. But the original data would be rubbish.

The value after string is not changed (so garbage is generated).

Variable character string: StringBuilder.

StringBuilder is modified on the original string, string creates a new string substitution.

Reason

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

Declaring and releasing reference-type variables

Frees the data using the keyword NULL (assigns an empty string).

After release, the garbage is formed, and it is automatically recycled.

Compare value types

In doing = = and! = when compared, the stored value (real data) is compared.

Comparing reference types

in do = and! = When comparing, the comparison is whether the location of the reference is the same, not the value referenced.

Enum type

Definition: Enumerates all the values of a data.

Function: Enhance the readability of the code, limit the value.

Applicability: Small range of values.

Use the enum keyword to define the enumeration 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, the value of each enumeration is incremented by 1 at a time, and the value can be modified once, incrementing the value of the subsequent enumerator.

The default underlying type of an enumeration element is int, and the type of enumeration allowed is byte, sbyte, short, ushort, int, uint, long, or ulong.

Type conversions

String type conversion to enumeration

Sex S1 = (sex) enum.parse (typeof (Sex), "male");

Enumeration to String

String str = Sex, female. ToString ();

int type to enum

Sex s2 = (sex) 3;

Enum type converted to int type

int i = (int) Sex. male;

Flag Enumeration

Multiple enumeration 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

Determines whether a value in the Flag enumeration contains an item

BOOL B = (S2 & sex. Male) = = sex. Male;

00011

00001

00001

String Manipulation Properties

Use S. The length property to get the number of characters in the string.

The contents of a string are immutable once declared. So it can only be read and cannot be modified.

To modify the contents of a string, first create a new string, using S. The ToArray () method gets a char array of strings, modifies the array, and then calls new String (char[]) to create a string of char arrays. Once the string is created, the modification of the char array does not cause the string to change.

StringBuilder variable string.

Common functions of the String class

Inserts a character into the string. Insert ();

Finds whether the character is in a character and returns a bool value.

ToLower (); Gets the lowercase form of the string.

Or

ToUpper (); Gets the uppercase form of the string.

Find string position

Take substring

Trim (); Remove white space characters at both ends of the string. Used to avoid user errors in the entry.

Two strings (SI, s2) ignore case comparisons.

Splits a string into a character array according to the specified Char delimiter, and stitching

ignores null characters after splitting a string into a character array according to the specified Char delimiter

Replace the individual contents of the string with replace.

Take substring

Practice:

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 reversal: 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);

Odd digit character uppercase even digit character lowercase:

String str = "I want to Learning";

string result = String. Empty;

Char temp= ' + ';

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);

. NET Foundation Chuanjiang

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.