1. C # basics: variables, operators, branches, loops, enumeration, arrays, methods,

Source: Internet
Author: User

1. C # basics: variables, operators, branches, loops, enumeration, arrays, methods,

I have been developing. net for five years and have gone through asp + access,. net + sqlserver, MVC + EF and other development modes. I plan to consolidate the system recently.

If there is something wrong with it, I hope you can point out that there are still some fallen knowledge points, please provide them. Thank you.

 

C #. Net and IDE Introduction

1. What is. Net?

. Net refers to the. Net Framework, a platform and a technology.

The. Net Framework is an indispensable part of the. Net platform. It provides a stable runtime environment to ensure the normal operation of various applications developed based on the. Net platform.

. NET Framework consists of two main components:. NET Framework class library and public language runtime.

CLR (Common Language Runtime Library): A modern runtime environment for managing user code execution. It provides services such as JIT compilation, memory management, exception management, and debugging.

CTS (general type system): defines the rules for declaring, defining, and managing all types, without considering the language

CLS (Public Language Specification): all. NET compilers must all support a set of minimum standards to ensure language interoperability instant (JIT) compilers compile MSIL code into native code specific to the target operating system and computer architecture

2. What is C #?

C # is a programming language that can be used to develop applications based on the. Net platform.

. Net is a multi-language development platform such as vb c ++ F #. It is mainly developed using the C # programming language.

Iii. What can. Net do?

1. desktop applications (Winform) are software.

2. Internet applications (ASP. NET) are websites.

3. Mobile development wp8

4. Unity3D Game Development

Iv.. Net Interaction Mode

C/S: Clinet/Server, client-to-Server software that needs to be installed on the computer.

B/S: Browser/Server. The Browser does not need to be installed on the computer and can be opened on the webpage.

5. What is IDE?

IDE is the development tool we use, and visual studio is the most commonly used one.

Use visual studio

Start method: double-click the icon and run the command devenu.

Create console project: Create a Project c # Name of the. net framework project in the upper-right corner of the console

Solution relationship: the solution contains multiple projects, multiple files in the project, the namespace in the file contains classes, the class can contain methods, and the method contains program code.

The. sln suffix file is a solution file that contains information about the entire solution. Class files end with. cs.

The. csproj project file contains the project information.

Right-click the solution, add a project, create a project, and append it to multiple projects in the solution. You can set a project to automatically start the project when it starts. The project can be detached and appended. When compilation is executed, no check is performed. the uninstalled project tool-> there is a reset development environment in the Import and Export settings, you can set the font row number.

Common shortcut keys: ctrl + k + d All alignment | ctrl + k + f partially alignment | ctrl + s save | ctrl + shift + s save all | ctrl + c copy | ctrl + v paste | ctrl + z undo | ctrl + y forward | ctrl + j intelligently prompts ctrl + w + ecode to automatically fold rows and so on.

Vi. Main Method

The Main method is the entry method of the program. When executing a program, first find the main method and start executing the first program in the main method. After the main method is executed, the program ends. A program can only have one main method.

Input and Output

Console. WirteLine (); // output a sentence to the Console. Console. ReadLine (); // enter a sentence to the Console.

Each sentence of code ends;

Start mode: f5 with debugging startup, shift + f5 does not start

Build solution compilation project F6

8. xmind Drawing Software

Create an empty tab key Add a subnode enter key Add a sibling Node

F7 quick F8 Preview

 

Basic syntax

I. Notes

// Single line comment ctrl + k + c ctrl + k + u cancel

/**/Multi-line comment

/// Document comment

# Region # endregion folding code

2. Software System dependency

Windows operating system-> Common Language Runtime Library CLR->. net Framework class library-> C #-> CLS Common Language Specification-> rules to be followed when translating to intermediate IL language CTS general type system-> have defined types

Iii. Variables

It is used to store data in the computer and in the memory. Memory is a temporary storage data loss in the memory when the power is down

The written code is stored in memory. After being saved to the hard disk, the variable represents a piece of memory space. You can use the variable name to store/retrieve data in the memory.

1. Declare Variables

Data type variable name;

Example: int a; string B; double c;

2. Variable assignment

Variable name = value; where "=" is the value assignment operator, which assigns the right value to the left variable.

For example, a = 1; B = "asd"; c = 2.13; minimum Priority a = a + 1; assignments are completed;

3. Declare and assign values

Data type variable name = value;

For example, int a = 1;

Variable values can be assigned repeatedly. The last time shall prevail, but the variable cannot be declared repeatedly.

Iv. Data Types

Integer: int, floating point: double, character: char, string: string, currency: decimal.

Double Precision 15 ~ The value is 16 bits and is not displayed after 16 bits. m/M is added after decimal precision 29; otherwise, an error is returned based on the double type.

V. variable naming rules

It must start with a letter or @ or a number. It can be followed by numbers, letters, and underscores.

It cannot be repeated with system keywords, be case sensitive, or be repeatedly defined.

If all abbreviated words are in the upper case of ICBC, the second multiple words are in the upper case and the first one is in the lower case of fuckYou? Or each of them is capitalized FuckYou!

Vi. Use of "+"

Add "+" Numbers (numbers on both sides). Example: 1 + 1

"+" String Link (one character string) Example: string result = "haha" + 123;

7. placeholders

"My name is {0}, height is {1}", one, two; the number of placeholders on the right must be the same as that on the left; otherwise, an error is returned.

In the console output, "," is used to replace placeholders.

8. variable exchange

Int a = 5, B = 10, temp;

Temp =;

A = B;

B = temp; // complete the exchange

9. escape characters

Special characters that can be output by adding a single character

\ "Output quotation marks \ n line feed \ B backspace key to delete the previous \ t tab key line alignment \ output \

Add @ to the front of the string to identify whether the string has \ escape, and the string can be wrapped. Two"

10. Arithmetic Operators

+-*/% Binary operators: two numeric operations

11. arithmetic expressions

The expression a + B is composed of two numbers connected by the operator.

12. type conversion

Implicit type conversion: it is also called automatic conversion. conversion occurs when the target type is greater than the source type. (Small to large)

Display type conversion: it is also called forced conversion. To convert double type to int type, do not decimal point [(data type) value] (large to small)

(Int) the string on the right must be an integer before conversion.

Convert Conversion

Convert. ToInt32 (with conversion string); // converts it to Int;

Convert. ToString (number); // Convert to a string

Each type has a. ToString (). You can also use this method to convert it to a string.

XIII,Can be empty type?
Int? A = null; indicates that the value of a can be null.

14. Exception Handling

Try {} catch: An error may be reported in try.

 

Operator

I. unary Operators

++ Auto-increment-auto-Subtraction

Plus ++; age = 18; sum = age ++-10; age ++ calculates age-10 before age ++ calculates age ++; age = 19 sum = 8;

+ + + Age-10 + + age

2. compound assignment operators

+ = * =/= % =

Age + = 3; Auto-increment 3 is similar to: age = age + 3;

Iii. Relational operators

> Greater than <less than = equal! = Not equal to> = greater than or equal to <= less than or equal

Two numbers of operations are called binary operators.

Iv. boolean type

The bool type has only two values: true and false.

The result of the relational operation is boolean.

5. logical operators

&: True if both the left and right expressions are true.

| Or: if either the left or right expression is true

! Non: true if not true

Vi. Ternary Operators

A1 = a2? "A": "B" sets up output a; otherwise, output B.

 

 

Branch Structure

I. If

If (condition)
{
Code to be executed;
}
The judgment condition is generally a value of the relational expression or bool type. If the judgment condition is true, the code in braces is executed.

II. If-else

If (condition)
{
Code
} Else {
Invalid code
}
If the conditions are true, execute the code in braces; otherwise, execute the code in else.

Iii. If-else If

Used to process interval judgments with multiple conditions

if(a=1){}else if(a=2){}else if(a=3){}else{} 

You always know whether else is actually absent.

Iv. Switch-case

Used to process equivalent comparison of multiple conditions

Switch (num)
{
Case 1: If 1
1
Break;
Case 2: If 2
2
Break;
Default: otherwise
Other
Break

}

 

Loop Structure

1. While Loop

Judge before execution

Int I = 0;
While (I <100) // Condition
{
I ++;
If (I = 50)
Break; // skip Loop
}

2. do-while loop

First execute recycling

Do
{
I ++;
} While (I <50 );

3. for Loop

For (int I = 1; I <10; I ++ ){
Console. writeline (I );
}

4. foreach Loop

Foreach (var item in list ){
Console. writeline (item. xx );
}

For a set of loops, see Chapter 2. It is a loop. If a large amount of data is stored, there is no for efficiency.

V. break, continue, and goto

Break immediately jumps out of the loop

Continue ends this next cycle

Go to the specified position

 

Constants, enumerations, structures, and Arrays

I. Constants

Unchangeable Value

Const type name = Value

Const pi = 3.14;

Ii. Enumeration

Restrict assignment values to select values in the set when enumeration is defined

Public enum Gender // defines Enumeration
{
Male,
Female
}

Gender gender = Gender. Male; // enumeration value assignment

When defining enumeration, the value cannot be of the int type.

Convert enumeration to int

The enumerated type can be converted to the int type. The enumerated type is compatible with the int type.

The enumerated value is defined with a default number, starting from 0.

(Int) Gender. Male; // The value is 0. Female increments by 1 at a time.

If a value is assigned when the default value of enumeration is changed, this value starts by default.

Public enum Gender // defines Enumeration
{
Male = 2,
Female
}

At this time (int) Gender. The male value is 2, and the female value is 3.

 

Enumeration type conversion

Int to Enumeration

Gender gender = (Gender) n1; If n1 is 0, male is output.

String type conversion to Enumeration

Gender gender = (Gender) (Enum. Parse (typeof (Gender), "male "));

Iii. Structure

Public struct Person // define the structure
{
Public string name; // define a field
Public string tel;
}

Person zsPerson; // use the structure
ZsPerson. name = "zs"; // Structure assignment
ZsPerson. tel = '123 ';

Iv. Array

Declare the array and specify the length

Data Type [] array name = new type [array length];

Value assignment array name [0] = 1;

Int type array from 0 default value 0

Array name. length get array length

Int [] nums = new int [10]; // defines an array

Nums [0] = 1;

Nums [1] = 2; // value assignment

Int lengt = nums. Length; // get the Length

For (int I = 0; I <nums. Length; I ++) // traverses the value

The length is not specified for direct value assignment during declaration.

String [] names = {"zhangsan", "lisi", "wangwu "};

String [] names = new string [3] {"zhangsan", "lisi", "wangwu "};

The array length must be equal to the value length.

String [] names = new string [] {"zhangsan", "lisi", "wangwu"}; // The array length can be omitted.

5. Bubble Sorting

Compare the elements in the array by commas (comparison between I and I + 1) after n (number-1 ).

From big to small sort, use less than comparison to exchange

Int [] nums = {1, 5, 23, 8, 5, 0, 4, 5}; for (int I = 0; I <nums. length-1; I ++) {for (int j = 0; j <nums. length-1-I; j ++) {if (nums [j] <nums [j + 1]) {int temp = nums [j]; nums [j] = nums [j + 1]; nums [j + 1] = temp ;}}for (int I = 0; I <nums. length; I ++) {Console. writeLine (nums [I]);} Console. readKey ();

 

Method

The method is to reuse a bunch of Code. There may be input values, returned values, and returned results after execution.

Methods are generally defined in the class. If the method does not return a value, void is used.

[Access modifier] [static] return Value Type method name ([parameter]) // [] can have no {return; // return}

 

Public static void showView () {Console. WriteLine ("Hello World! ");} // Static call class. showView (); I. variable scopeGlobal variables are defined in all methods in the class. General static methods are used to define static local variables. Ii. ParametersNumber of parameters. The type must be the same as int. parse (string) is similar to Convert. toInt32 (string) static void Main (string [] args) {test ("Diavd", 18);} public static void Test (string name, int age) {Console. writeLine ("my Name is {0}, Age is {1}", name, age );} Iii. return valuesPublic static string Test (int a) {if (a = 1) {return "1" ;}else {return "other" ;}} the return value must be the same as the return type. Iv. Method OverloadingThe number or type of parameters with the same method name may be independent of the return value. static void Main (string [] args) {int m = Max (10, 20); double d = Max (10.3, 20.3) ;}public static int Max (int one, int two) {if (one> two) {return one ;}else {return two ;}} public static double Max (double one, double two) {if (one> two) {return one ;}else {return two ;}} V. outReturns a value. The parameter return value is passed out. // you can directly use static void Main (string [] args) {int number without assigning a value in the method; // number is 20; int result = test (out number);} // number can be used without a value assignment. You also need to write out
Static int test (out int a) {a = 20; // if the method parameter name is marked as out, it must be assigned a value in the method. Return a;} int number = int. Parse ("a12"); // if it fails, an exception is thrown.
Int result; int number2 = int. TryParse ("a12", out result); // the string is converted first, and the second returns whether the conversion is successful; Vi. refWhen the value in the reference transfer method is changed, static void Main (string [] args) {int number = 100; test (ref number) is also changed ); // after execution, the number is 500} static void test (ref int a) {int B = a; // use a = 500 directly without assigning a value to; // In this case, the value is not a variable value, but the memory address side is number, which is equivalent to creating a shortcut instead of copying a copy} VII. Variable params ParametersPublic void test (string name, params int [] ages)
{

}
// Variable call array Length
Test ("a", 12, 12 );
Test ("B",); variable parameters must be the last parameter in the parameter list VIII. Method RecursionCall the public int Sum (int n) command to Recursively search for disk files by yourself ){
If (n <= 0 ){
Return 0;
}
Return n + Sum (n-1 );
} // 1 + 2 + 3 +... + n and

 

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.