Reflection on the method of passing. NET parameters, caused by passing. net Parameters

Source: Internet
Author: User

Reflection on the method of passing. NET parameters, caused by passing. net Parameters

The following is a brief introduction to some of the common parameter usage of. NET. If you have any questions, I hope you can correct them. You are also welcome to leave a message to discuss them and share your own opinions.

1. DotNet parameter Overview:

In. NET, the parameter (formal parameter) variable is part of the method or indexer declaration, and the real parameter is the expression used to call the method or indexer.

In CLR, all method parameters are passed by default. When an object of the reference type is passed, the reference to an object is passed to the method. Here, the ship reference itself is passed to the method by passing the value. This also 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 sent to the method. This means that the method will obtain a dedicated Value Type instance copy, and the instances in the caller will not be affected.

In CLR, parameters can be passed by passing references rather than passing values. In C #, out and ref are used to pass references. In C #, The out and ref parameters are used to transmit reference values. These two keywords tell the compiler to generate metadata to indicate that the parameter is referenced, the compiler will generate code to pass the parameter address, instead of passing the parameter itself. For the value type, use out and ref. The effect is equivalent to passing the reference type by passing the value.

Common parameters include basic type parameters, generic parameters, and<In T> and <out T>, dynamicAnd so on. For example, <in T> and <out T> support generic type variability in CLR, and C # obtains the syntax required for the life generic at 4.0, now the compiler can understand the possible conversions between interfaces and delegation. Variability is a type-safe method in which one object is used as another object. Variability is applied to generic interfaces and generic delegate type parameters. The covariant is used to return the value of an operation to the caller. The inverter refers to the caller who wants to pass in the API value. The immutability is relative to the covariant and inverter, and it means nothing happens. I have a wealth of knowledge in this area. If you are interested, you can understand it on your own. I will not detail it here. Dynamic type. C # Is a static language. In some cases, the C # compiler must look for a specific name rather than an interface. Dynamic can do anything during compilation and then be processed by the framework during execution. The introduction of dynamic types is not described in detail.

In. NET, parameters are mainly used as optional parameters, named parameters, variable quantity parameters, and so on. The following describes how to use these three parameters.

Ii. DotNet parameter usage:

The following describes the usage of three parameters: optional parameters, named real parameters, and variable quantity parameters.

1. Optional parameters:

(1). Basic usage:

If an operation requires multiple values, and some values are often the same during each call, you can use optional parameters. Before C # implements the Variable Parameter Function, it often declares a method that contains all possible parameters. Other Methods call this method and pass the appropriate default value.

In optional parameters, you can assign default values to some or all parameters when designing a method parameter. When calling these method codes, you can choose not to specify some real parameters and accept the default values. When calling a method, you can also specify the parameter name to pass the real parameter. Example:

 static void OptionalParameters(int x, int y = 10, int z = 20)  {   Console.WriteLine("x={0} y={1} z={2}",x,y,z);  }
 OptionalParameters(1, 2, 3);   OptionalParameters(1, 2);   OptionalParameters(1);

In the preceding example, we can clearly see its usage. int y = 10 and int z = 20 are optional parameters. If a parameter is omitted during the call, the C # compiler automatically embeds the default value of the parameter. When passing real parameters to a method, the compiler evaluates the real parameters in the order from left to right. When a named parameter is used to pass a real parameter, the compiler evaluates the real parameter from left to right.

(2). Basic Principles:

Optional parameters include the following specifications:

(). All optional parameters must appear after the required parameters, except the parameter array (declared using the params modifier), but they must appear at the end of the parameter list, before they are optional parameters.

(B). The parameter array cannot be declared as optional. If the caller does not specify a value, it will be replaced by an empty array.

(C). Optional parameters cannot use the ref and out modifiers.

(D ). optional parameters can be of any type, but there are some restrictions on the specified default value, that is, the default value must be a constant (number or string literal, null, const Member, enumeration member, default (T) operator ).

(E). The specified value is implicitly converted to the parameter type, but this conversion cannot be user-defined.

(F). You can specify the default value for parameters with parameter properties, methods, constructors, and parameters that are part of the delegate.

(G). C # real parameters between commas cannot be omitted.

When you use an optional parameter, use null as the default value for the reference type. If the parameter type is a value type, you only need to use the corresponding null type as the default value.

(3). Sample Code:

/// <Summary> /// extract the exception and its internal exception stack trace // </summary> /// <param name = "exception"> extract the exception </param> /// <param name = "lastStackTrace"> last extracted stack trace (for recursion ), string. empty or null </param> /// <param name = "exCount"> Number of extracted stacks (for recursion) </param> /// <returns> limit E. string </returns> public static string ExtractAllStackTrace (this Exception exception, string lastStackTrace = null, int exCount = 1) {while (true) {var ex = effectio N; const string entryFormat = "# {0 }:{ 1} \ r \ n {2}"; lastStackTrace = lastStackTrace ?? String. empty; lastStackTrace + = string. format (entryFormat, exCount, ex. message, ex. stackTrace); if (exception. data. count> 0) {lastStackTrace + = "\ r \ n Data:"; lastStackTrace = exception. data. cast <DictionaryEntry> (). aggregate (lastStackTrace, (current, entry) => current + $ "\ r \ n \ t {entry. key}: {exception. data [entry. key]} ") ;}// recursively add an internal exception if (ex = ex. innerException) = null) return lastStackTrace; exception = ex; lastStackTrace = $ "{lastStackTrace} \ r \ n"; exCount = ++ exCount ;}}

2. Named arguments:

The following describes some basic concepts and usage of optional parameters. Next, let's take a look at the operation usage of the Parameter Name:

(1). Basic usage:

A named real parameter is a parameter name that can be specified at the same time when the value of the real parameter is specified. The compiler checks whether the parameter name is correct and assigns the specified value to the parameter. Name parameters are added with their parameter names and a colon Before each real parameter. The following code:

new StreamWriter(path:filename,aooend:true,encoding:realEncoding);

If you want to specify a name for a parameter that contains ref and out, you need to put the ref and out modifiers after the name and before the real parameter.

int number;bool success=int.TryParse("10",result:out number);

(2). Basic Principles:

In the named parameters, all named parameters must be placed after the real parameter of the location, and the location between the two cannot be changed. The positional arguments always point to the corresponding parameters in the method declaration. You cannot skip the parameters and specify them by naming them. Real parameters are still evaluated in the written order, even if the order may be different from the declared order of parameters.

In general, optional parameters and named arguments are used together. Optional parameters increase the number of applicable methods, while named arguments reduce the number of methods used. To check whether a specific method is applicable, the compiler constructs a list of passed real parameters in sequence using location parameters, and then matches the named real parameters with the remaining parameters. If a required parameter is not specified, or a named real parameter cannot match the remaining parameter, this method is not applicable.

Naming arguments can sometimes replace forced conversions to assist the compiler in heavy-load decision-making. If the method is called from outside the module, changing the default value of the parameter is potentially dangerous. Real parameters can be passed to parameters without default values by name. However, to compile the Code, all required real parameters must be passed.

When writing C # code to interoperate with the COM object model, the optional parameters and named parameters of C # are the best. When calling a COM component, in order to pass a real parameter as a reference, C # also allows omitting REF/OUT. When the COM component is used for callback, C # requires that the OUT parameter be applied to the real parameter. REF keyword.

3. Pass variable parameters:

In project development, sometimes we need to define a method to obtain variable parameters. You can use params. params can only be applied to the last parameter in the method signature. The params keyword tells the compiler to apply the System. ParamArrayAttribute instance to the parameter. Let's take a look at the implementation code:

[AttributeUsage(AttributeTargets.Parameter, Inherited=true, AllowMultiple=false), ComVisible(true), __DynamicallyInvokable]public sealed class ParamArrayAttribute : Attribute{ // Methods [__DynamicallyInvokable] public ParamArrayAttribute();}[__DynamicallyInvokable]public ParamArrayAttribute(){}

The code above shows that this class inherits from the Attribute class and may not be unfamiliar with the Attribute class, that is, the base class for defining custom attributes. It indicates that the ParamArrayAttribute class is used to define custom attributes, the ParamArrayAttribute class is in the System namespace. The ParamArrayAttribute class has only one constructor and has no specific implementation. AttributeUsage also defines how to use attributes.

C # When the compiler detects a method call, it checks all methods with the specified name and the parameter does not apply ParamArrayAttribute. If a matching method is found, the compiler generates the Code required to call it. If the compiler does not find a matching method, it will directly check the method that applies ParamArrayAttribute. If a matching method is found, the compiler constructs an array in code, fills in its elements, and generates code to call the selected method.

When a variable number of parameters is called, some extra performance losses may occur. The array object must be allocated to the upper part, the array elements must be initialized, And the Array Memory must be eventually recycled.

Provides a method code for reference only:

/// <Summary> // convert a two-dimensional array to a able // </summary> /// <param name = "stringDyadicArray"> </param> /// <param name = "messageOut"> </param> // <param name = "ableablecolumnsname"> </param> /// <returns> </returns> public DataTable DyadicArrayToDataTable (string [,] stringDyadicArray, out bool messageOut, params object [] ableablecolumnsname) {if (stringDyadicArray = null) {throw new ArgumentNullExceptio N ("stringDyadicArray");} var returnDataTable = new DataTable (); if (dataTableColumnsName. Length! = StringDyadicArray. getLength (1) {messageOut = false; return returnDataTable;} for (var dataTableColumnsCount = 0; dataTableColumnsCount <dataTableColumnsName. length; dataTableColumnsCount ++) {returnDataTable. columns. add (dataTableColumnsName [dataTableColumnsCount]. toString ();} for (var dyadicArrayRow = 0; dyadicArrayRow <stringDyadicArray. getLength (0); dyadicArrayRow ++) {var addDataRow = returnDataTable. newRow (); for (var dyadicArrayColumns = 0; dyadicArrayColumns <stringDyadicArray. getLength (1); dyadicArrayColumns ++) {addDataRow [ableablecolumnsname [dyadicArrayColumns]. toString ()] = stringDyadicArray [dyadicArrayRow, dyadicArrayColumns];} returnDataTable. rows. add (addDataRow);} messageOut = true; return returnDataTable ;}

The preceding example shows how to use variable parameters and named parameters to convert a two-dimensional byte array into a able object, traverse the array, and write the array into the DataTable object, the logic of the entire method is not described in depth, and the code is relatively simple.

Iii. Guiding Principles related to parameters:

When declaring the parameter type of a method, specify the weakest type, preferably the interface rather than the base class.

Among the basic principles of the design model, the dimit rule is also a minimum knowledge principle. The dimit rule means that if two classes do not need to communicate with each other directly, they should not interact directly. If one class needs to call a method of another class, it can be forwarded by a third party. In the design of the class structure, each class should minimize the access permissions of members. The weaker the Coupling Degree between classes, the more conducive to reuse. A class with weak coupling is modified and will not affect related classes.

In the use of parameters, we still need to think carefully and seriously about the use of parameter types, because in the definition of parameter types, to some extent, it affects the scalability and stability of our programs. If the parameter type constraints are large, it is of great significance for the extension of subsequent methods. In the entire object-oriented language system, all design patterns are extended by "polymorphism", and many interfaces and delegation are used in our object-oriented design, the purpose is to expand the constraint of parameters during use.

In the return type of a method, the returned type should be declared as the strongest type, so as not to be limited by a specific type.

Iv. Summary:

The above is a brief introduction to method parameters. The content of this article mainly introduces optional parameters and named parameters. If there are any deficiencies in the above content, I hope you will be able to find out the corresponding problems. Knowledge prevails over model, and then reflection. After learning a little bit, we need to sum up and reflect on the meaning of the content, so that we can have time, energy, and ability to think about it.

The above is a small series to introduce to you. NET parameter transmission method, hope to help you, if you have any questions, please leave a message, xiaobian will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.