C # Study Notes (compared with Java, C, C ++, and Python)

Source: Internet
Author: User

C # Study Notes (compared with Java, C, C ++, and Python)
Recently I am going to learn about Unity3D, and select C # in C # and JavaScript #. Therefore, as a preparation for learning Unity3D, you must first learn C #. It took a day or two to learn C #. It seems that it is a language between C ++ and Java. It is more flexible than Java and simpler than C ++. It is indeed a well-designed language. Basic concepts and syntax basic data types in C # are divided into value type and reference type. Compared with Java, the number of unsigned characters is added, and the struct in C is also the basic type. Numeric, enumeration, and struct are value types. Strings, objects, arrays, and delegates are reference types. The basic data types in C # all have corresponding packaging classes. During compilation, the compiler converts the basic type to the corresponding class, for example, int corresponds to Int32, string corresponds to String. Unlike Java, keywords of the basic type only correspond to the alias of the class, so the variables of the basic type also have their own methods. C # You can convert numeric types. The conversion rules are similar to those in Java and C/C ++. Note that bool and int in C # cannot be converted. The basic type includes the static method Parse converted to itself. In addition, C # has a dedicated Convert class that can be used for type conversion. The constant keywords in C # are const and readonly. The former is determined during compilation and must be assigned a value during declaration. The latter is determined at runtime and can be assigned once after declaration. Naming Convention the name of a function is the upper case of a letter, and the lower case of a variable. In C #, the entry method is the Main method with uppercase letters. Pre-compiled instructions can be used in C. For example, # define, # if, and pragma. However, # define cannot be used to define constants, but can only be used to define symbols. The namespace of namespace C # is not much different from the command space of C ++. If you have studied Java or Python, the concepts in both are similar. Type inference uses the var keyword, similar to auto in C ++. It is determined during compilation that the program performance will not be affected. The basic input/output is more concise than Java: using System ;//... console. read (); // Read a single character Console. readLine (); // read a row of Console. write (); // Write the Console without line breaks. writeLine (); // write and wrap the line to implement nextXXX in Java: Read a row and use the split method of string to cut it, and convert it to the corresponding type. A basic switch statement requires a break for each case unless the case is empty. C # The goto keyword can be used in the switch. Add the foreach keyword. The IEnumerable interface must be implemented for the object. The usage is the same as for: foreach (var v in list) {// do something.} in Python .} character string special symbols \ and @: @ can cancel the escape in the character string, similar to the r before the character string in Python. C # uses the placeholder {x} instead of the % syntax to represent the variables in the output. x starts from 0. Methods Self-Contained in string: Substring (int startindex, int len) Replace (string oldValue, string newValue) Split () ToCharArray (int startindex, int len) ToUpper () and ToLower () = and! = C # also has the StringBuilder class. Its usage is similar to that in Java. Arrays are the same as arrays in Java. arrays in C # are also objects and have their own attributes and methods. C # declare common multi-dimensional arrays and staggered arrays (arrays of arrays ). Note that the declaration method is as follows: int [,] arr1 = new int [3, 5]; int [] [] arr2 = new int [3] []; for (int I = 0; I <arr2.Length; I ++) {arr2 [I] = new int [I + 1];} C # also has a class Array similar to the Arrays class in Java. Unsafe, fixed, checked, and unchecked can insert Insecure code through unsafe, and the C/C ++ pointer can be used in the code. It can be used in a method or code block. Fixed indicates that the garbage collector should not move objects in the code to avoid errors. It is generally used in insecure code. Checked and unchecked: in the checked context, Algorithm Overflow causes an exception. In unchecked context, the Algorithm Overflow is ignored and the result is truncated. Function visibility is private by default. Added internal, which is visible within the namespace. Parameter and return value numeric type and struct are passed by value. For other types, such as objects and arrays, COPY Copies referenced by itself. The above is the same as passing parameters in Java. The ref keyword is added to C # and a method for modifying real parameters in the method is provided, similar to references in C/C ++. Write a Swap as follows: static void Swap (ref int x, ref int y) {int t = x; x = y; y = t ;} // call the Swap method Swap (ref num1, ref num2). Use the params keyword to implement variable length parameter transfer. This parameter must be placed at the end of the parameter list and the type is array. Addition example of a variable length parameter: static int Sum (params int [] arr) {int sum = 0; foreach (int I in arr) sum + = I; return sum ;} // call the Sum method int sum = Sum (1, 3, 5, 7, 9); C # also supports output parameters, expressed in out. In this way, multiple parameters can be returned, which is more elegant than Java and safer than C/C ++. Example of calculating the Division to obtain the quotient and remainder: static void Divide (int n, int d, out int q, out int r) {q = n/d; r = n % d ;} // call the Divide Method Divide (n, d, out q, out r). The operator overload C # supports Operator overloading. The usage is the same as that of C/C ++. For example, the string in C # implements the = overload, so the = can be used to directly compare the content of the two strings. Delegate function pointers similar to C/C ++. You can encapsulate existing methods through delegation. The procedure for using the delegate is as follows: Define the function type: delegate int Operation (int val1, int val2); declare the variable of this type: Operation failed; instantiate the variable: public int Add (int val1, int val2) {return val1 + val2;} public int Subtract (int val1, int val2) {return val1-val2;} if (operator = '+ ') alias = new Operation (Add); elseation = new Operation (Subtract); Call int res = values (val1, val2); lambda expressions get anonymous methods by delegate. But the simpler method is to use lambda expressions. The lambda expression format is: x =>{// do something with x} x is the input parameter. The compiler can automatically infer the type of the lambda expression. If no parameter is input, use () instead. Comparison between classes and objects and struct: struct has its own attributes and methods, which can be seen as lightweight classes. Struct inherits from System. ValueType and the class inherits from System. Object. Struct cannot implement abstraction and inheritance, and cannot declare non-argument constructor or destructor. It can be created using new or not. Getter/setterC # provides getter and setter, which are simpler than Java. Example: private string name; // internal variable public string Name {get {return name;} set {name = value ;}} you can write the corresponding getter/setter in get and set. Here, value is a keyword that refers to the parameters passed in by the user. More simply, you can not specify the internal variable: public int Age {get; set;} public string Name {get; set;} inheritance and polymorphism C # Only support single inheritance. Both inheritance and implementation are represented. In C #, the base keyword is used in the same way as the super keyword in Java. You can use base () to call the corresponding constructor of the parent class. Use base. XXX () to call the XXX method of the parent class. The ban class is inherited. Java uses the final keyword, and C # uses sealed. C # To implement polymorphism, you also need to declare the parent class method as virtual and declare it as override in the subclass method to realize polymorphism.

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.