[CLR via C #] 9. Parameters

Source: Internet
Author: User

When designing parameters for a method, you can assign default values to some or all parameters. Then, when calling the code of these methods, you can choose not to specify some real parameters and accept the default values. In addition, when calling a method, you can also pass real parameters for it by specifying the parameter name. For example:

    Int32 s_n =    M(Int32 x=, String s = = (DateTime), Guid guid =         M(,       M(      M(s_n++, s_n++      M(s: (s_n++).ToString(), x: s_n++}
If the default value is specified for some parameters in the defined method, note the following principles: 1) methods, constructor methods, and parameter attributes (C # indexer) specify the default value. You can also specify the default value for parameters that are part of the delegate definition. Then, when you call a variable of the delegate type, you can omit the real parameter to accept the default value. 2) parameters with default values must be placed after all parameters without default values. In other words, once a parameter with a default value is defined, all parameters on its right must also have a default value. But there is an exception: "parameter array" must be placed after all parameters (including those with default values), and the array itself cannot have a default value. 3) The default value must be a constant value that can be determined during compilation. The types of these parameters can be primitive types recognized by C #, including enumeration types, and any reference types set to null. For a parameter of any value type, you can set the default value to an instance of the value type and make all its fields contain zero values. You can use the default keyword or the new keyword to express this meaning. For example, if you set the default values of dt and guid parameters in the M method, these two types of syntax are used. 4) do not Rename (I .e. modify) the parameter variable name. Otherwise, any caller passing real parameters by passing parameter names must modify their code. 5) if the method is called from outside the module, changing the default value of the parameter may pose a potential risk. The caller embeds the default value in its call. If you change the default value of the parameter later, but do not re-compile the code of the caller, it will pass the default value when calling your method. You can set the default value to 0/null as the Sentinel value to occupy the seat. 6) if the parameter is identified using the ref or out keyword, the default value cannot be set. Because there is no way to pass a meaningful default value for these parameters. When using optional or named parameters to call a method, pay attention to the following principles: 1) real parameters can be passed in any order; however, named real parameters can only appear at the end of the real parameter list. 2) You can pass real parameters by name to parameters without default values. 3) C # It is not allowed to omit real parameters between good conditions, such as M (1, DateTime. Now ). 4) if the parameter requires ref/out, use the following syntax to pass the real parameter by passing the parameter name:
     M( Int32 a = 

 

In C #, once a default value is assigned to a parameter, the compiler will apply a custom attivity, namely System. Runtime. InteropServices. OptionalAttribute, internally like this parameter. This attribute is permanently stored in the metadata of the final generated file. In addition, the compiler will reference a parameter named System. runtime. interopServices. attribute ultparametervalueattribute attribute and store the attribute persistence in the metadata of the final file. Then, the constant value you specified in the source code is passed to the parameparametervalueattribute constructor. Then, once the compiler finds that some real parameters are missing in a method call, it can determine that the optional real parameters are omitted, and extract their default values from the metadata to automatically embed these values into the call. Then, once the compiler finds that some real parameters are missing in a method call, it can be determined that optional real parameters are omitted and Their default values are extracted from the metadata, these values are automatically embedded in the call.

 

For a local variable of the implicit type in a method, C # allows you to determine its type based on the type of the initialization expression.

   name =        x = (Exception);         ShowVariableType(x);               numbers =  Int32[] { , , ,        collection =  Dictionary<String, Single>() { { ,  ( item 
A local variable of the implicit type is a local variable and cannot be used to declare parameters of the method. A field of the type cannot be declared. The local variables declared with var are just a simplified syntax that requires the compiler to deduce the specific data type based on an expression. The var keyword can only be used to declare local variables in a method, while the dynamic keyword can be used to declare local variables, fields, and parameters. The expression cannot be transformed into var, but dynamic. You must initialize the variables declared by var, but do not need to initialize the variables declared by dynamic. By default, CLR assumes that all method parameters are passed values. When an object of the reference type is passed, the reference to an object (or pointer to the object) will be passed to the method. However, this reference (or pointer) is passed to the method by passing values. This means that the method can modify the object, and the caller can see these changes. For a value-type instance, a copy of the instance is passed to the method, which means that the method will obtain a copy of a dedicated value-type instance, and the instances in the call will not be affected. In CLR, parameters can be passed by passing references rather than passing values. In C #, the keyword out and ref are used. Both of these keywords tell C # The metadata generated by the compiler to indicate that the reference is passed when the parameter is specified. The compiler will generate code to pass the parameter address, instead of passing the parameter itself. From the CLR perspective, the keyword out is exactly the same as that of ref. This means that no matter which keyword is used, the same IL code will be generated. In addition, the metadata is almost consistent. Except for one bit, it is used to record whether to specify out or ref when declaring a method. C # The Compiler treats two keywords differently, and the difference determines which method is responsible for initializing the referenced object. If the method parameters are marked with out, the caller is not expected to initialize the object before calling the method. The called method cannot read the parameter value and must be written to this value before return. On the contrary, if the method parameters are marked with ref, the caller must initialize the parameter value before calling the method. The called method can read or write the value. For the value type, use out and ref. The effect is equivalent to passing the reference type by passing the value. For value types, out and ref allow methods to manipulate a single value type instance. The caller must allocate memory for the instance, and the caller can manipulate the content in the memory. For the reference type, the call code allocates memory for a pointer (the pointer points to an object of the reference type), and the caller can manipulate the pointer. Because of this, it makes sense to provide out and ref for the reference type only when the method "returns a reference to an object known to the" method. 4. When passing variable parameters to a method, the developer wants to define a method to obtain variable parameters. To declare a method to accept variable numbers of parameters, see the following:
     Int32 Add(=  (Int32 x = ; x < values.Length; x+++=

We can call it like this:
  Console.WriteLine(Add( Int32[] { , , , ,  }));

  Console.WriteLine(Add(, , , , ));
This can be done because the params keyword exists. The params keyword tells the compiler to reference an instance of System. ParamArrayAttribute to the parameter. Only the last parameter of the method can be marked with the params keyword (ParamArrayAttribute. In addition, this parameter can only identify an array of any type. You can pass a null value for this parameter or a reference to an array containing another element.
 ));
What if I write a method to obtain any number or type of parameters? You only need to modify the method prototype to get an Object [] instead of Int32 []. For example
   DisplayTypes( (Object o 

 

1) when declaring the parameter type of a method, specify the weakest type, preferably an interface rather than a base class. For example, if you want to write a method to process a set of data items, it is best to use an interface (such as IEnumerable <T>) to declare the parameters of the method, instead of using strong data types (such as List <T>) or stronger interface types (such as ICollection <T> or IList <T> ):
          MainpulateItems<T>(IEnumerable<T>      MainpulateItems<T>(IEnumerable<T>           ProcessBytes(Stream someStream) { ... }

 

2) It is generally best to declare the return type of the method as the strongest type, so as not to be limited by a specific type. For example:

             Stream ProcessBytes() { ... }
The first method is preferred. It allows the caller of the method to regard the returned object as a FileStream object or a Stream object. However, the second method requires the caller to regard the returned object as a Stream object. In short, make sure that the caller has as much flexibility as possible when calling the method, so that the application scope of the method is greater.

 

6. Constants

CLR does not support constant parameters/objects.
 

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.