3. C # CORE Programming structure

Source: Internet
Author: User

This study mainly refers to Andrew Troelsen's C # and. NET4 advanced Programming, this section mainly tells the following things: This section is a supplement to the previous section, mainly related to the knowledge of the details: 1, C # method of various details 2, explore out, The ref and params keywords, as well as optional parameters and named Parameter 3, method overloads. 4. C # Manipulate the details of the array type and understand the features contained in the System.Array class type. 5. Enumeration structure and struct type. 6. The difference between a value type and a reference type. 7. Explore the types of nullable data and the?? The function of the operator. The method and parameter modifiers are similar to the main method, and custom methods can have or have no parameters, or they can have or have no return values. Methods can be implemented within the scope of a class or struct (you can also set prototypes in an interface type), and can be decorated by various keywords (such as internal, virtual, public, and so on) to limit their behavior. The basic format of the method is as follows: class a{static int Add (int x,int y) {return x+y;}} Next summarize the C # parameter modifiers. 1. Default parameter passing behavior: the default behavior of a parameter passed into a function is passed by value. Simply put, a copy of the data is passed into the function if there are no modifiers associated with the parameter tag parameter. Numeric data is a value type, so if you change the value of the parameter within the scope of the member, and the change is a copy of the caller's data value, the caller will not be aware of this change at all. 2.out modifier: In simple terms, it is the output parameter. It is obligatory to define a method with an output parameter before exiting this method,must beAssign an appropriate value to the parameter. For example, the following method returns X/Y and to ans: static void Add (int x, int y, out int ans) {    ans=x+y;} The out parameter has a useful purpose that callers can use to return multiple return values in a single method. Also, calling a method with an output parameter requires an out modifier. 3.ref modifier: To say what I understand, the use of the REF keyword is equivalent to the ability to have value types that have similar reference types, usually changing their values. The following is the difference between a reference parameter and an input parameter: The output parameter does 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. 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 # supports the use of parameter arrays using the params keyword. The params keyword can pass a variable number of arguments (the same type) as a single logical parameter to the method. For example, the following method: Static double calculate (params double[] values) {} This method is defined as a parameter array with a double type and can pass any number of double type parameters to it. Example: Calculate (4.1,4.2,...) Note: To avoid ambiguity, the C # requirement method supports only one params parameter, and must be the last parameter of the parameter list. 5. Defining Optional Parameters: Basically, we can create a parameter that contains the default value assigned. For example, the following method: static void A (string A, string b= "SB") {} where the second parameter is an optional parameter to which we have assigned a default value. Similarly, in order to avoid ambiguity, an optional parameter must be placed at the end of the method signature, and an optional parameter before a non-optional parameter throws a compilation error. 6. Calling methods with named arguments: As with optional parameters, the primary reason for supporting named parameters is also to simplify interoperability with COM. Named arguments allow us to specify the values of parameters in any order when calling a method, so we can use the colon operator to specify parameters by name instead of passing parameters by location. The parameters are used as follows: For example, define a B method 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, the named parameter is very useful, and when you call the method, We simply assign a value to the named parameter, so we don't have to specify the value of the optional parameter. 7. Member overloading: And other object-orientedLanguage, C # allows method overloading. In short, when we define a group of members with the same name, if their number (or type) is different, such a member is called an overloaded member. For example, the B method of the same name, the passed parameter is an int type, and the other is a double type, which is also allowed. b (int aa) and B (double aa) are two different methods. Differentiated by the type of the parameter. An array manipulation array in  c# is a set of data items that are accessed through a numeric index. More precisely, an array is a set of data points of the same type (int array, string array, and so on). The array definition is similar to the following: int[] myintarray; usage such as: int[] myintarray=new int[3]; assignments such as int[0]=199;1.c# array initialization syntax: In addition to populating arrays verbatim, you can also populate arrays with array initialization syntax. By specifying each array item within the curly brace {}, use the following: string[] Mystrarray = new string[] {"A", "B"};2. Implicitly typed local arrays: Var can also be used to define implicitly typed local arrays, which are defined as follows (note that The element type of an array must be the same, so even an implicitly typed array, the type of the inner element is consistent, because the type is determined at compile time: var Mystrarray = new[] {"A", "B"};3. Define an Object array: Because System.Object is the final base class for all types in the. NET type system, if we define an object array, its subkeys can be anything. Usage is as follows: object[] obj = new object[] {1, "a", ' a '};4. Using multidimensional arrays: There are two main types of multidimensional arrays, one is called a rectangular array. One is called a jagged array. The rectangular array is arranged in the form of a matrix, declared as follows: Int[,]=new int[6,6]; represents a rectangular array that declares a 6*6. A jagged array, which is an array of arrays. The declaration is as follows: int[][] = new int[5][]; declares an array with five different arrays. 5. Arrays as parameters (and return values) as long as we create an array, we can simply pass it as an argument or accept it as a member return value. As follows: Static string[] A () {    string[] B = new string[]{"AAA"};    return B;} 6.system.array base class: Each of the arrays we create is from the SYStem. The array class gets a lot of functionality. With these public members, we can manipulate arrays using a uniform pair of item models. (Clear (), Sort (), and so on) For example, to invert an array, operate as follows: string[] A = new string[]{"A", "B"}; Inversion usage: array.reverse (A);  enumeration type when building the system, It is convenient to create a set of symbolic names that correspond to known numeric values. Enumeration can help us implement this function. By default, the storage type of the enumeration value is System.Int32. The definition is as follows: Enum e{sss=12,//means that starting from 12 aaa,//True Value 13bb//True value is 14}1. Control the underlying storage of enumerations: The storage type of the enumeration value can also be changed, if we set the enumeration value storage type to byte instead of int, So you can write this: enum e:byte{aaa=10,b=1,cc=100} Note that if we have enumerated values that are outside the scope of the enumeration type, it will result in a compilation error. As above, a compilation error is thrown if the enumeration value equals 999.  2. Declaring enumeration variables: Because enumerations are simply user-defined types, we can use them as return values for functions, method parameters, local variables, and so on. 3.system.enum type:. NET enumerations derive a lot of functionality from this class, which defines a number of methods used to query and transform an enumeration. For example, the Enum.getunderlyingtype () method, which is used to return the data type used to hold the value of an enumeration type. 4. Dynamically get enumeration name/value pairs: All enumerations Support the ToString method, which returns the string name of the current enumeration value. Another method, GetValue, can return the value of the enumeration.   structure type As with the structure in C, structs are not just a set of name-value pairs, but they can contain many data fields and the types of members that manipulate those fields. Define structure: struct a{    public int x;    public void Disp ()     {        Consol E.writeline ("x={0}", X);   }} Create a struct variable: the first can be defined directly as a struct name, such as A; but this must be assigned to each public field in the structure, otherwise an error occurs. Another method is to create a struct variable with the new keyword, which invokes the default constructor and does not accept any input parameters. A = new A ();  value type and reference type C # nodeand arrays, strings, and enumerations are all derived from System.ValueType. The purpose of this is to ensure that all derived classes are allocated on the stack and not on the garbage collection heap. The creation and destruction of data on the allocation stack is fast, because its lifecycle is determined by the defined scope, and the data allocated on the heap is monitored by the. NET Laki collector, with many determinants of its life cycle. Functionally, the only purpose of the class is to override the virtual method defined by System.Object to use value-based rather than reference-based syntax. Because value types use value-based syntax, the life cycle of a structure can be predictable, and it is immediately removed from memory when the structure variable leaves the scope of the defined field. 1. Value type, reference type, and assignment operator: value type Assignment (for example, structure), two copies are kept on the stack, one operation is changed, and the value of the other copy is not affected. When you apply an assignment operator to a reference type (class type) compared to a value type in a stack, we are redirecting the reference variable in memory. They are equivalent to referencing the same object in the managed heap, and the other changes when one of the values is changed. 2. A value type that contains a reference type: By default, when the value type contains other reference types, the assignment generates a copy of the reference. This will have two separate structures, but each contains a reference to the same object in memory (shallow copy). The ICloneable interface needs to be implemented if you want to perform a ' deep copy ' that means that the copy is not affected by itself and the state of the internal reference is completely copied to a new object. 3. Passing a reference type by value: It's about passing the class as a parameter to the method, and modifying the class's parameters and re-assigning them several times inside the method. Example: Class a{    public int a;    public A (int aa)     {        A = Aa;&nbs P  }} method B is as follows: void B (A a) {    A.A = 100;//means changing the value inside the class, functioning     A=new A (99),//representing the class being re-assigned, does not work} because, here, the value passed in it is a reference to the object that copied the caller. Because the B method points to the same object as the caller, it is possible to change the state data of the object, but the reference cannot be re-assigned to a new object. 4. Passing reference types by reference: Refer to the example above, if there is a C method, it is passed reference type by reference. such as: void C (ref a A) {    A.A = 100;//indicates a changeThe value of a in the class, which functions     a=new A (99);//indicates that a new object is assigned to a instance of a heap, and the golden rule to remember when passing reference types by reference is as follows: 1, if the reference type is passed by reference, The callee may change the value of the object's state data and the referenced object. 2, if a reference type is passed by value, the callee may change the value of the object's state data, but cannot alter the referenced object.  c# Nullable types Now we should remember that all numeric data types (including the Boolean data type) are value types, and by rule Null is used to establish an empty object reference, so value types can never be assigned null. To define a nullable variable type, you should add a question mark (?) to the underlying data type. As a suffix. Note that this syntax is only valid for value types. If you attempt to create a nullable reference type, including a string, you are encountering a compilation error. As with non-null variables, local nullable variables must be assigned an initial value. 1. Use nullable types: when it comes to database programming, nullable data types can be particularly useful because columns in one data table might be intentionally empty. The definition is as follows: public int? A=null; return nullable type: public int? Geta () {    return A;} 2.?? Operator: The last thing you need to know about nullable types is that you can use the?? Operator. When the obtained value is actually null, we can use this operator to assign a value to a nullable type. For example, when the above method returns a value of NULL, the local variable can be assigned a value of 100: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 () is set, if (!a.hasvalue)     a = 100; Console.WriteLine ("A value is: {0}", a);  summary: This summary summarizes the C # keywords that you can use to build a custom method, by default the parameters are passed by value. However, if the parameter is marked as ref or out, we can pass it by reference. In addition to that, I've also summarized methods for method overloading, as well as how arrays, enumerations, and structs are defined in C # and represented in the. NET class library. Finally, we've got the value type and reference type details, and how they react when passed in as parameters, and how to use??? operator to interact with a nullable data type.

3, C # Core programming structure

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.