C # Study Notes 1,

Source: Internet
Author: User
Tags bitwise operators

C # Study Notes 1,

1.This attribute allows access to the program name and any parameters specified on the command line when the current process is started. The program name can (but is not required) contain path information. You can use the Environment. GetCommandLineArgs () method to retrieve the command line information that is analyzed and stored in the string array.

string cmd = Environment.CommandLine;Console.WriteLine(cmd);

2.The difference between the decimal type and the C # floating point type is that the base of the decimal type is decimal, and the base of the floating point type is binary. A decimal is expressed as ± N × 10k (k power,-28 <= k <= 0), where N is a positive integer of 96 bits. A floating point number is any number of ± N × 2 k (k power), where N represents a positive integer with a fixed number of BITs (float is 24, double is 53, k is-149 ~ + 104 (float) or-1075 ~ + Any integer of 970 (double.

3.All data of the string type, whether or not it is a string literal, is immutable (or unchangeable), for example, you cannot change the string "Come As You Are" to "Come As You Age ". That is to say, you cannot modify the data that the variable originally references. You can only assign a value to the variable again to point it to a new location in the memory.

(1) You can use the @ symbol before a string to indicate that the escape sequence is not processed. In this way, the generated result is a literal string, which not only treats the backslash as a common character, it can also be interpreted as a blank character by word.

(2) output the characters required for a new line. Use the "\ r \ n" character combination or Environment. NewLine.

Console.WriteLine(@"begin                               /\                                /  \                               /    \                /______\end");

4.Char supports assignments in four formats. char can be implicitly converted to ushort, int, uint, long, ulong, float, double, or decimal. However, there is no implicit conversion from other types to char Types.

Char [] chars = new char [4]; chars [0] = 'X'; // character chars [1] = '\ x0058 '; // hexadecimal chars [2] = (char) 88; // numeric conversion chars [3] = '\ u0058'; // Unicodeforeach (char c in chars) {Console. write (c + "");} Console. writeLine (ushort) '\ x0020'); Console. writeLine (0x2A); // In a hexadecimal number, '0x 'is required as the prefix Console. writeLine ("0x {0: X}", 42); // use x or X to convert a 10-digit number to a hexadecimal number, the case sensitivity determines the size of the hexadecimal display letters. writeLine ("\ 0, N"); // "\ 0" indicates Null

5.In. Net2.0, you can use the default () operator to determine the default value of a data type.

6.Arrays are divided into common (one-dimensional) arrays, multi-dimensional arrays, and staggered arrays (variable arrays, I .e. arrays of arrays, which must create an array instance for each internal array ), the declaration method is as follows.

(1) Use Length to return the total number of array elements. Therefore, if you have a multi-dimensional array, such as the cells [,] array with a size of 2x3x3, Length returns 18 elements in total. You can use Rank to check the dimension of an array, and use GetLength (int) to check the total number of elements in a dimension.

(2) Before using the Array. BinarySearch () method, it is necessary to sort the Array. If the values are not sorted in ascending order, an incorrect index is returned.

(3) The Array. Clear () method does not delete the elements of the Array and does not set the length to zero. The array size is fixed and cannot be modified. Therefore, the Clear () method sets each element in the array as its default value (false, 0. Null ).

String [] language = {"C #", "COBOL", "Java", "C ++", "Visual Basic", "Pascal", "Fortran ", "Lisp", "J #"}; int [,] cells = {1, 0, 2}, {1, 2, 0}, {1, 2, 1 }}; int [] [] cells2 = new int [4] [] {new int [4], new int [3], new int [2], new int [1]}; Array. sort (language); string searchString = "COBOL"; int index = Array. binarySearch (language, searchString); Console. writeLine ("The wave of the future, {0}, is Index {1 }. ", searchString, index); Console. writeLine (); Console. writeLine ("{0,-20} {1,-20}", "First Element", "Last Element"); Console. writeLine ("{0,-20} {1,-20}", "-------------", "------------"); Console. writeLine ("{0,-20} {1,-20}", language [0], language [language. length-1]); Array. reverse (language); Console. writeLine ("{0,-20} {1,-20}", language [0], language [language. length-1]); Array. clear (language, 0, Language. length); Console. writeLine ("{0,-20} {1,-20}", language [0], language [language. length-1]); Console. writeLine ("After clearing, the array size is: {0}", language. length); Trace. assert (4.2f! = 4.2); // The Trace class provides a set of methods and attributes to help you track code execution.

7.Goto statement: it directly transmits program control to the mark statement.

(1) A common usage of goto is to pass the control to a specific switch-case label or the default label in the switch statement.

(2) The goto statement is also used to jump out of a deep nested loop.

Note:Although goto can also be used outside the switch statement, they usually lead to poor program structure and should be replaced with a structure that is easier to understand. Note that, you cannot use a goto statement to jump from outside the switch language to a label inside the switch statement. In general, C # prohibits a goto from going into something, so it can only be used within something, or used to jump out of something. Through this restriction, C # avoids most abuse of goto in other languages.

static void TestGoto(){    Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");    Console.Write("Please enter your selection: ");    int n = Console.Read();    int cost = 0;    switch (n)    {        case 1:            cost += 25;            break;        case 2:            cost += 25;            goto case 1;        case 3:            cost += 50;            goto case 1;        default:            Console.WriteLine("Invalid selection.");            break;    }    if (cost != 0)    {        Console.WriteLine("Please insert {0} cents.", cost);    }    Console.WriteLine("Thank you for your business.");    Console.WriteLine("Press any key to exit.");}static void TestGoto2(){    int x = 200, y = 4;    int count = 0;    string[,] array = new string[x, y];    for (int i = 0; i < x; i++)        for (int j = 0; j < y; j++)            array[i, j] = (++count).ToString();    Console.Write("Enter the number to search for: ");    string myNumber = Console.ReadLine();    for (int i = 0; i < x; i++)        for (int j = 0; j < y; j++)            if (array[i, j].Equals(myNumber))                goto Found;    Console.WriteLine("The number {0} was not found.", myNumber);    goto Finish;    Found:    Console.WriteLine("The number {0} is found.", myNumber);    Finish:    Console.WriteLine("End of search.");    Console.WriteLine("Press any key to exit.");}

8.Bitwise OPERATOR: assume there are two numbers. The bitwise operator starts from the leftmost bit and performs logical operations by bit until the rightmost bit, the value 1 at a position is regarded as true, and the value 0 is regarded as false. The binary values of 12 AND 7 are represented as follows: 20171100,00000111. Therefore, if the bitwise AND (&) operation is performed on the two values, the first operation number (12) is compared by bit) and the second operand (7), get the binary value 00000100, that is, the decimal 4. The bitwise OR (|) Operation of the two values is 00001111, that is, 15 in decimal format. The result of bitwise XOR (^) is 00001011, that is, 11 in decimal format. The true is true when both "&" and "|" are true when either of them is true, and true when "^" is true.

Byte and, or, xor; and = 12 & 7; // bitwise operators can also be combined with value assignment operators, such as and | = 7; or = 12 | 7; xor = 12 ^ 7; Console. writeLine ("bitwise calculation result of 12 and 7, and = {0}, or = {1}, xor = {2}", and, or, xor );

9.Shift Operator: "<", ">" is used to shift the binary data of a number.

Const int size = 64; char bit; Console. write ("Enter an integer:"); var value = ulong. parse (Console. readLine (); ulong mask = 1ul <size-1; // here, the mask is the 63 power of 2, and the binary value is 63 zeros behind 1, while the maximum value of ulong is the 64 power of 2 and then minus 1, for (int count = 0; count <size; count ++) {bit = (mask & value)> 0 )? '1': '0'; // here, the binary value of the mask is only 1, and the other value is 0. After bitwise XOR or, only 1 will be greater than 0Console. write (bit); mask >>=1;} Console. writeLine (); Console. writeLine ("-9 binary {0}", Convert. toString (-9, 2); // converts a 32-bit integer to its binary string representation Console. writeLine ("8 binary unsigned inversion: {0 }",~ (Uint) 8); // The return type is int, uint, long, And ulong. bitwise inverse operators are opposite to each bit of the operand.

10.Compare two values: when comparing the two values for equality, the inaccuracy of the floating point type (float, double) may cause very serious consequences. Sometimes, the values that should have been equal are incorrectly judged as not equal.

decimal number1 = 4.2m;float number2 = 0.1f * 42f;double number3 = 0.1 * 42;Console.WriteLine("number1=number2 : {0}", (float)number1 == number2);Console.WriteLine("number2=number3 : {0}", number2 == number3);

11.Note: The position of the increment or decrement operator determines whether the assigned value is the value before or after the calculation of the operand, which affects the operation of the Code, if you want the value of result to include the result of an ascending (or descending) calculation, You need to place the operator before the variable you want to increment. However, the variable value changes regardless of the prefix or suffix.

12.Logical boolean operators, including And (&), Or (|), XOR (^), Not (!), ^ Is an exclusive OR operator. If it is applied to two Boolean operands, the XOR operator returns true only when only one of the two operands is true.

13.C # pre-processor commands are called during compilation. The pre-processor Command tells C # compiler to compile the code and shows how to handle specific errors and warnings. It can also be the difference between different platforms, for example, using # if in windows and linux to treat different system APIs differently; Preprocessor commands can also be used in debugging, for example, use the # if debug command to enclose the debugging code. Preprocessor Commands include # if (# endif), # elif, # else, # define (Declaration command), # under (cancel command definition), and # error (specify generation error), # warning (specify to generate a warning), # pragma (disable or recover # warning command), # line (change the row number displayed by the compiler when an error or warning is reported), # region (# endregion ).

14.During a foreach loop, the compiler prohibits you from modifying iteration variables.

-------------------------- The above content is organized according to the C # Third Edition of the essence.

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.