1. C # Basics: Variables, operators, branches, loops, enumerations, arrays, methods < go >

Source: Internet
Author: User

Turn from: Pirate Captain

Links: http://www.cnblogs.com/baidawei/p/4701504.html#3241882

C#. NET and introduction to the IDE

First, what is. Net?

. NET refers to the. NET Framework framework, a platform, a technology.

The. NET Framework framework is an integral part of the. NET platform, and it provides a stable operating environment to ensure that the various applications we develop based on the. NET platform function properly.

Differences between versions of the. Net Framework

2002 1.0------VS2002

Unified type System, base Class library, garbage collection, multi-language support, ADO 1.0, ASP. 1.0, WinForm 1.0.

2003 1.1------VS2003

Security upgrades, with support for ODBC Oracle, support for IPv6

2005 2.0------VS2005

Improves security, performance, generics and built-in generic collections, expansion of base class libraries, introduction of transaction transaction

2006 3.0------requires 2.0 framework support

WCF (Web Service), WF (Workflow), WPF (user interface Unified), WCS (Digital identity user control)

2007 3.5------VS2008

ASP. NET AJAX, Linq, automatic properties, object initializers, collection initializers, extension methods, lambda expressions, query syntax, anonymous types, Linqtosql, MVC

2010 4.0------VS2010

DLR, dynamic, default parameters, named parameters, parallel development, etc.

The. NET Framework consists of the. NET Framework class library and the common language runtime two main components

CLS (Common Language Specification): Used to guarantee compatibility between languages, as long as the components written in any. NET language that follows the CLS can be referenced by other languages.

CTS (Common type System): Defines the rules for data types such as numbers, strings, and arrays so that they can be shared by all. NET languages.

CLR (Common language Runtime): Only used to execute intermediate language code. Then compile them into machine language so they can execute on the current platform.

DLR (Dynamic Language Runtime): A new feature of 4.0, the CLR provides a common platform for C # and VB, while the DLR provides a common platform for COM components such as JavaScript and Ruby.

Second, what is C #?

C # is a programming language that can be developed based on. NET platform applications.

. NET is a multi-language development platform VB C + + F, etc., mainly in the C # programming language for development.

Three. NET can do?

1, desktop application (Winform), is the software.

2. Internet application (ASP) is a Web site.

3, mobile phone development WP8

4. Unity3d Game Development

Four. NET Interactive mode

C/s:clinet/server, the client-to-server software that needs to be installed on the computer.

B/s:browser/server, browser to the server, do not need to be installed on the computer, open through the Web page.

V. What is an IDE?

The IDE refers to the development tools we use, and Visual Studio is the most common one.

Visual Studio Uses

Start mode: Double-click icon, command: devenv

Create a console project: New Project C # console in the upper-right corner. NET Framework version project name

Solution Relationships: A solution contains multiple projects, a project contains multiple files, a namespace in a file contains a class, a class can contain a method, and a method contains program code.

The. sln suffix file is a solution file that contains information for the entire solution. class file ends with. cs.

The. csproj project file contains information about the project.

Solution Right-click New Project when new project is appended to a solution multiple projects can be set when a project starts automatically when a startup project is started the project can be uninstalled and appended when you do compile no longer check the unloaded Project tool, the import export setting has a reset development environment where you can set the font line number 。

Common shortcut keys: ctrl+k+d all Alignment | Ctrl+k+f Partial Alignment | Ctrl+s Save | Ctrl+shift+s All Save | CTRL + C Copy | Ctrl + V Paste | CTRL + Z Undo | Ctrl+y Forward | Ctrl+j Smart Tips ctrl+w+e Code Auto-wrapping and so on.

VI. Main method

The Main method is the entry method for the program. When executing a program, first find the main method, starting with the first sentence in the main method, and then the program ends when the main method is finished executing. A program can have only one main method

Input/Output

123 Console.WirteLine(); //向控制台输出一句话。Console.ReadLine();  //向控制台输入一句话。

Every line of code to; end

Starting mode: F5 with Debug start, Shift+f5 does not start

Build Solution Compile Project F6

Eight, xmind drawing software

New Empty Tab key new sub-node enter new sibling node

F7 Quick F8 Preview

Basic syntax

First, comments

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

/* * * Multi-line Comment

Document comments

#region #endregion Folding Code ctrl+k+s #reg

Second, configure the C # compilation environment

C # source programs require the C # compiler csc.exe provided by the. NET Framework SDK installer to compile, and environment variables need to be set.

My Computer-Properties-System Properties-advanced-environment variables-system environment variables-System variables-Select path-Point edit-Add the SDK installer path to the variable value.

C:\Windows\Microsoft.NET\Framework\v4.0.30319//my paths in path;

CMD into the source file directory input CSC xxx.cs The directory will be compiled into Xxx.exe executable CD C:\Users\ David \desktop\abc\abc---> csc Program.cs

Third, variable

Used to store data in the computer, stored in memory. Memory is temporarily stored when data is lost in memory during power outage

The code is written in memory, saved from memory to the hard disk after saving the variable represents a piece of memory space, you can store/fetch data to memory through the variable name.

1. Declaring variables

Data type variable name;

Example: int A; String B; Double C;

2. Assigning values to variables

Variable name = value; where "=" is the assignment operator, the right-hand value is assigned to the left variable.

Example: a = 1;b = "ASD"; c = 2.13; The lowest priority a=a+1;

3. Declaring and assigning values

Data type variable name = value;

Example: int a = 1;

Variables can be assigned repeatedly, whichever is the last, but not repeating variables that must be declared before using

Iv. Types of data

Integer: int, floating-point number: Double, character: Char, string: String, Currency: Decimal.

Double precision 15~16 bit, 16 no longer display, decimal precision 29 followed by m/m Otherwise, the double type error.

4.0 new Features

System.Numerics.BigInteger large integer type requires framework 4.0 or above if the BLL does not check whether the assembly is referenced

BigInteger big = new BigInteger (1000000000);
Long value = 31313892839283;
BigInteger big = value;

Dynamic Data type

Data types are not checked at runtime

Dynamic v = 124;

Console.WriteLine (V.gettype ()); System.Int32

Five, variable naming rules

Must start with a letter or _ or @ and not begin with a number. It can be followed by numbers, letters, and underscores.

Can not be duplicated with system keywords, case sensitive, can not be repeated definition.

If an abbreviated word is all capitalized in ICBC, the second word in multiple words is capitalized first lowercase fuckyou? or each capital fuckyou!

Vi. use of the "+" sign

"+" numbers added (both left and right are numbers) example:

"+" string link (with one string) Example: string result = "haha" + 123;

Seven, placeholder

"My name is {0}, height {1}", One,two; The right side guarantee is the same as the left placeholder or the error

The "," in the console output is followed by the replacement of the placeholder

Eight, variable Exchange

int a = 5,b = 10,temp;

temp = A;

A = b;

b = temp; Complete the Exchange

Nine, escape character

A special character that can be output by \ plus a character

\ "Output quotation mark \ n line \b Backspace backspace key to delete the previous \ t tab line alignment \ \ output \

string preceded by @ identifies the string with \ No longer escaped, string can be wrapped, output "two"

Ten, arithmetic operators

+-*/% two operator two digit operation

Xi. Arithmetic expressions

The expression is composed of two-number-a+b operator links

12. Type Conversion

Implicit type conversions: Also called auto-conversions, which occur when the target type is larger than the source type. (a small turn into a large)

Display Type conversions: Also called casts, cast double to int do not decimal "(data type) value" (large turn into small)

(int) The string to the right of string must be an integer before it can be converted.

Convert conversion

Convert.ToInt32 (with conversion string);//convert to int;

convert.tostring (number); Convert to String

Type has one. ToString () can also be converted to a string using this method

13, nullable type?
Int?  A = null; A value that represents a can be null using the

14. Exception Handling

Try{}catch may have errors in try to enter catch

Operator

One or one-tuple operator

+ + self-increment-self-reduction

After ++;age=18; sum = age++-10; age++ the first value before calculating the age-10 operation and then calculating age++; Age=19 sum=8;

Front + +; ++AGE-10 ++age Fetch new value first + finish

Two, compound assigns the value character

+= += *= /= %=

age+=3; From add 3 similar to: age=age+3;

Third, relational operators

> greater than < less than = = equals = = is not equal to >= greater than or equal to <= less than equals

Two-number operation called a two-tuple operator

Iv. Types of Booleans

A bool type has only two values: True True, false false.

The result of a relational operation is a Boolean type of

Five, logical operators

&&: True if both left and right expressions are established

|| Or: The left and right expression has a set to True

! Non: TRUE if not established

Six or three-tuple operator

a1= =a2? "A": "B" set up output a otherwise output b

Branching structure

First, If

if (judging condition)
{
The code to execute;
}
The judging condition is generally the value of the relationship expression or bool type, and the code in curly braces is executed if the condition is determined.

Second, If-else

if (judging condition)
{
The established code
}else {
Non-established code
}
If the condition is determined, execute the code inside the curly braces, otherwise execute the else code.

Third, If-else If

Interval judgment for dealing with multiple conditions

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

You know, always judging if there is really nothing else.

Iv. Switch-case

Equivalence comparison to handle multiple conditions

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

}

Loop structure

One, while loop

Judge and execute first.

int i = 0;
while (i<100)//condition
{
i++;
if (i==50)
Break Jump out of the loop
}

Second, Do-while cycle

Perform recirculation first

Do
{
i++;
}while (I<50);

Third, for Loop

Cycle of the specified number of times

for (int i = 1;i<10;i++) {
Console.WriteLine (i);
}

Four, foreach Loop

Loop Collection

foreach (var item in list) {
Console.WriteLine (item.xx);
}

The collection of loops is in the second chapter, and it's a loop. There's a lot of data without a for efficiency.

V. Jump statements

Break immediately jumps out of the loop

Continue end this time the next cycle

Goto jumps to the specified location

return returns

Throw throw exception

Constants, enumerations, structs, and arrays

One, constant

Non-changing values

Const type NAME = value

Const pi=3.14;

Second, enumeration

Limit assignment to select values in the collection when the enumeration is defined

public enum Gender//Definition Enumeration
{
Man
Woman
}

Gender Gender = Gender. Male; Enumeration assignment

When defining an enumeration, the value cannot be of type int, and that does not make sense.

enum to int

enumerated types can be converted to and from int types, and enum types are compatible with int types.

The value of an enumeration is defined by a default number, starting at 0.

(int) Gender. Male; A value of 0 women is 1 increments of 1 per

When you change the default value definition of an enumeration, the value is assigned by default.

public enum Gender//Definition Enumeration
{
Male =2,
Woman
}

At this point (int) Gender. Male value is 2, female is 3.

Enum type conversions

Int converted to Enumeration

Gender Gender = (Gender) N1; The N1 is 0 when the male is output.

String type conversion to enumeration

Gender Gender = (Gender) (Enum.parse (typeof (Gender), "male"));

Third, structure

public struct person//define Structure
{
public string name; Defining fields
public string Tel;
}

Person Zsperson; Working with structures
Zsperson.name = "ZS"; Structure Assignment
Zsperson.tel = ' 138484848448 ';

Four, array

Declaring an array and specifying the length

data type [] array name =new type [array length];

Assignment array name [0]=1;

Array of type int starting from 0 default value 0

Array name. length Get array Lengths

int [] Nums = new INT[10]; Defining arrays

Nums[0] = 1;

NUMS[1] = 2; Assign value

int lengt = Nums. Length; Get the length

for (int i=0; i< nums. Length; i++)//Traversal value

Direct assignment at declaration does not specify length

String[] names = {"Zhangsan", "Lisi", "Wangwu"};

string[] names = new String[3] {"Zhangsan", "Lisi", "Wangwu"};

The array length needs to be equal to the value length.

string[] names = new string[] {"Zhangsan", "Lisi", "Wangwu"}; Array length can be omitted

Five, bubble sort

Compares element 22 in an array (i vs. i+1) through N (number-1) comparisons

From large to small sort with less than comparison established on 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++) {&NBSP;&NBSp;  console.writeline (Nums[i]);} Console.readkey ();

Method

A method is a mechanism for reusing a heap of code, which may have input values, return values, and return results after execution.

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

[Access modifier] [Static] Return value type method name ([parameter])//[] can be no {return;//return}

public static void ShowView () {Console.WriteLine ("Hello world!");} Static statically called Class.showview (); One, variable scopeGlobal variables defined to all methods in a class the use of definitions in general static methods also uses static local variables in which method the definition is used second, the parametersThe number of arguments, the same type as int. Parse (String) resembles 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);} third, return valuepublic static string Test (int a) {if (a = = 1) {return "1";    } else {return "other"; }} The return value is the same as the return type. Iv. Method OverloadingMethod names with the same number of parameters or different types can constitute a return value independent of 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;     }} Five, outUsed to return a value, outgoing through the parameter rebate//You can use the static void Main (string[] args) {int number in the method without assigning values, and the//number is already 20; int result = Test (out number);} Number can be used without assignment, and must be written out when called
The 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");//Throws an exception if it fails.
int Result;bool number2 = Int. TryParse ("A12", out result); The first conversion string, the second returns the successful value of the conversion, or a failure of 0; Returns whether the value succeeds true false; Vi.. RefThe value inside the reference pass method changes the outside also will change the static void Main (string[] args) {int number = 100; Test (ref number); After execution, number is 500}static void Test (ref int a) {int b = A;//does not assign a value directly using a = 500;//This is not a variable assignment but the memory address edge is number equivalent to creating a shortcut Not a copy} seven, params variable parameterspublic void Test (String name,params int[] ages)
{

}
Variable call array length
Test ("a", 12,12,12);
Test ("B", 13,2), variable argument must be the last parameter of parameter list 4.0 new feature 1. Optional Parameters parameter values can be omitted for optional parameters, and each optional parameter has a default value as part of the definitionpublic void ABC (int num1,int num2,string oper = "+") where num1,num2 is a required parameter, Oper is an optional parameter, default is + when not entered 2. Named parameters can not be called in order when parameters are calledpublic void ABC (int num1,int num2,int num3) ABC (NUM2:123,NUM3:123,NUM1:123); Viii. method RecursionCall yourself more for recursive lookup disk file public int Sum (int n) {
if (n<=0) {
return 0;
}
return n + Sum (n-1);
}//1+2+3+. +n and

1. C # Basics: Variables, operators, branches, loops, enumerations, arrays, methods < go >

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.