3. C # under the core programming structure,

Source: Internet
Author: User
Tags array definition

3. C # under the core programming structure,
For more information, see Andrew Troelsen's C # And. NET4 advanced programming, This section describes the following: This section is a supplement to the previous section, mainly involves the knowledge details: 1. Various details of the C # method 2. Explore the out, ref, and params keywords, optional parameters and naming parameters 3. Method overloading. 4. C # operate on the Array type and understand the functions contained in the System. Array class type. 5. Enumeration structure and structure type. 6. Differences between the value type and the reference type. 7. Explore empty data types and? And ?? Operator. The method and parameter modifier are similar to the Main method. A custom method can have or has no parameters, or has or does not return values. Methods can be implemented within the scope of classes or structures (you can also set a prototype in the interface type), and can be used by various keywords (such as internal, virtual, public, etc) modify to limit its behavior. The basic format of the method is as follows: class A {static int Add (int x, int y) {return x + y ;}} next we will summarize the parameter modifiers of C. 1. default parameter passing behavior: the default behavior of passing a parameter to a function is passing by value. Simply put, if there is no modifier related to the parameter tag, the data copy will be passed into the function. The value data belongs to the value type. Therefore, if you change the parameter value within the scope of the member, the change is a copy of the caller's data value, and the caller is not aware of this change. 2. out modifier: in short, it is the output parameter. A method with an output parameter is obligated to assign an appropriate value to the parameter before exiting the method. For example, the following method returns the sum of x/y to ans: static void Add (int x, int y, out int ans) {ans = x + y ;} the out parameter has a very useful purpose. The caller can use it to return multiple return values at a time. In addition, the out modifier is also required to call a method with output parameters. 3. ref modifier: In my understanding, the usage of the ref keyword makes the value type have the function similar to the reference type, and usually changes their values. The following is the difference between the reference parameter and the input parameter: the output parameters do not need to be initialized before they are passed to the method, because the method must assign a value to the output parameter before exiting. The reference parameters must be initialized before they are passed to the method, because a reference to an existing variable is actually passed. 4. params modifier: C # uses the params keyword to support the use of parameter arrays. The params keyword can pass a variable number of parameters (of the same type) as a single logical parameter to the method. For example, the following method: static double calculate (params double [] values) {} is defined as an array of double-type parameters. You can pass any number of double-type parameters to it. For example: calculate (4.1, 4.2,...) Description: to avoid ambiguity, C # requires that the method only support one params parameter and must be the last parameter in the parameter list. 5. define optional parameters: in general, we can create a parameter that contains the default value. For example, the following method: static void A (string a, string B = "SB") {}. The second parameter is an optional parameter with A default value. Similarly, to avoid ambiguity, the optional parameter must be placed at the end of the method signature. If you put the optional parameter before the non-optional parameter, a compilation error occurs. 6. Call methods using named parameters: like the optional parameters, the main reason for supporting named parameters is to simplify the interoperability with COM. Naming parameters allow us to specify the parameter values in any order when calling a method. Therefore, we can use the colon operator to specify parameters by name without passing parameters by position. The parameter usage is as follows: for example, define a method B that passes the ConsoleColor parameter. Void B (ConsoleColor aaa); then you can use this method: B (aaa: ConsoleColor. white); if you define a method that contains an optional parameter, it is very useful to name the parameter. When you call this method, you just need to assign a value to the name parameter, you no longer need to specify the value of the optional parameter. 7. Member overloading: similar to other object-oriented languages, C # allows method overloading. In short, when we define a group of members with the same name, if their parameter quantity (or type) is different, such members are called overloaded members. For example, in Method B with the same name, the input parameter is of the int type and the input parameter is of the double type, which is also allowed. B (int aa) and B (double aa) are two different methods. The parameter types are different. The Array Operation Array in C # is a set of data items accessed through digital indexes. More accurately, an array is a group of data points of the same type (int array, string array, etc ). The array definition is similar to the following: int [] myIntArray; usage example: int [] myIntArray = new int [3]; Value assignment example: int [0] = 199; 1.C# array initialization syntax: in addition to filling the array word by word, you can also use array initialization syntax to fill the array by specifying each array item in curly brackets {}. The usage is as follows: string [] myStrArray = new string [] {"A", "B"}; 2. implicit type local array: var can also be used to define the implicit type local array. The definition method is as follows (note that the element type of the array must be the same, so even an implicit type array, the types of the internal elements must be consistent, because the types are determined during compilation.): var myStrArray = new [] {"A", "B"}; 3. define the object array: Because System. object is. all types of final base classes in the. net system. In this way, if an object array is defined, its subitem can be anything. Usage: object [] obj = new object [] {1, "A", 'A'}; 4. multi-dimensional array: There are two types of multi-dimensional array: rectangular array. An array is called an interleaved array. The arrangement of rectangular arrays is in the form of a matrix. The declaration is as follows: int [,] = new int [6, 6]; A 6*6 rectangular array is declared. An array, that is, an array. The Declaration is as follows: int [] [] = new int [5] []; declares an array with five different arrays. 5. As long as an array is created as a parameter (and return value), it can be passed as a parameter or accepted as a Member return value. Static string [] A () {string [] B = new string [] {"aaa"}; return B;} 6. system. array base class: Every Array we create is from System. the Array class provides many functions. With these public members, we can use a unified item model to operate arrays. (Clear (), Sort (), etc.) for example, to reverse an array, the operation is as follows: string [] A = new string [] {"A", "B "}; reverse usage: Array. reverse (A); it is convenient to create A group of symbolic names to correspond to known numeric values when constructing the system for enumeration types. Enumeration helps us implement this function. By default, the storage type of the enumerated values is System. Int32. Definition: enum E {sss = 12, // indicates aaa starting from 12, // the actual value is 13bb // the actual value is 14} 1. control the underlying storage of enumeration: The storage type of enumeration values can also be changed. If we set the storage type of enumeration values to byte instead of int, we can write it as follows: enum E: byte {aaa = 10, B = 1, CC = 100} note that if the enumerated value is out of the enumerated type range, compilation errors will occur. If you set the enumerated value to 999, a compilation error occurs. 2. Declare enumeration variables: Because enumeration is only a user-defined type, we can use them as function return values, method parameters, local variables, and so on. 3. System. Enum type:. net enumeration gets many functions from this class. This class defines many methods for querying and converting an enumeration. For example, the Enum. GetUnderlyingType () method is used to return the data type used to save the enumerated type value. 4. Dynamically Retrieve enumeration name/value pairs: All enumerations support the ToString method, which returns the string name of the current enumerated value. Another method, GetValue, can return the enumerated value. The structure type is the same as that in the C language. The structure is not only a group of name-value pairs, but also can contain many data fields and the types of members who operate these fields. Definition structure: struct A {public int x; public void Disp () {Console. writeLine ("x = {0}", x) ;}} create A structure variable. The first type can be defined by a structure name, for example, A; however, this must assign values to each public field in the structure. Otherwise, an error will occur. Another method is to use the new keyword to create a structure variable. It calls the default constructor and does not accept any input parameters. A a = new A (); the structure, array, string, and enumeration of the value type and reference type C # are all derived from System. ValueType. The role of this function is to ensure that all derived classes are allocated on the stack rather than the garbage collection stack. The data on the allocation and restack is created and destroyed quickly, because its lifecycle is determined by the defined scope, and the data allocated to the stack is determined. net pull-based recycler monitoring has many factors that determine its lifecycle. In terms of function, the only purpose of this class is to rewrite the virtual method defined by System. Object to use value-based instead of reference-based syntax. Because the value type uses the value-based syntax, the lifecycle of the structure can be predicted. When the structure variable leaves the scope of the defined field, it will be immediately removed from the memory. 1. value Type, reference type, and value assignment operator: Value Type assignment (such as structure), two copies are retained on the stack, and the value of one operation is changed without affecting the value of the other copy. Compared with the value type in the stack, when the value operator is applied to the reference type (class type), we are the point of the referenced variable in the memory. They reference the same object in the managed heap, and change the value of one of them. 2. Include the value type of the reference type: by default, when the value type contains other reference types, the value assignment will generate a reference copy. In this way, there are two independent structures, but each one contains references pointing to the same object in the memory (Shortest copy ). If you want to keep 'deep replicase', that is, to make the replicas independent, you need to implement the ICloneable interface when you want to completely copy the state of the internal reference to a new object. 3. Pass the reference type by value: It is probably to pass the class as a parameter to the method, and modify the class parameters and assign values multiple times within the method. Example: class A {public int a; public A (int aa) {a = aa ;}} Method B is as follows: void B (A a) {. a = 100; // indicates changing the internal value of the class. a = new A (99); // indicates re-assigning a value to the class and does not work.} because, here, the passed value actually copies the reference of the caller object. Because Method B and the caller direct to the same object, it is possible to change the object state data, but the reference cannot be re-assigned to a new object. 4. Pass the reference type by reference: refer to the example above. If there is a C method, it transmits the reference type by reference. For example, void C (ref A) {. a = 100; // indicates changing the value of a in the class, and a = new A (99); // indicates allocating a new heap object to instance, action} when passing a reference type by reference, you need to remember the following golden rules: 1. If you pass a reference type by reference, the caller may change the value of the object's State data and the referenced object. 2. If the reference type is passed by value, the caller may change the value of the object's State data, but cannot change the referenced object. C # Empty type now we should remember that all numeric data types (including Boolean data types) are value types. According to the rules, null is used to create an empty object reference, therefore, the value type cannot be assigned null. To define an empty variable type, add a question mark (?) to the underlying data type (?) Suffix. Note that this syntax is valid only for the value type. If you try to create a null reference type, including strings, you will encounter compilation errors. Like a non-empty variable, an initial value must be assigned to a partial empty variable. 1. Use of the void type: when programming in a database, the void data type may be particularly useful because columns in a data table may be intentionally empty. The definition is as follows: public int? A = null; null type: public int? Geta () {return a;} 2 .?? Operator: the last point you need to know about the null type is, can you use ?? Operator. When the obtained value is actually null, we can use this operator to assign a value to a null type. For example, if the return value of the preceding method is null, you can assign a value of 100 to the local variable: int a = geta ()?? 100; Use ?? The advantage of the operator is that it is more compact than the traditional if/else condition. However, you can also use the following code to ensure that if the value is null, the default 100: int a = geta (); if (! A. hasValue) a = 100; Console. writeLine ("the value of a is {0}", a); summary: This summary mainly summarizes the C # keywords that can be used to build custom methods, by default, parameters are passed by value. However, if the parameter is marked as ref or out, it can be passed by reference. In addition, I also summarized method overloading and how arrays, enumerations, and structures are defined in C # and represented in. net class libraries. In the end, we will discuss the details of the value type and reference type, including how they respond to and use the method when passed in as a parameter? And ?? Operator to interact with NULL data types.

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.