. NET parameter pass in the way of detailed

Source: Internet
Author: User
Tags dotnet modifiers object model stack trace

Here is a brief introduction. NET some commonly used parameter usage, if has the insufficiency also to correct, also welcome everybody in the following message discussion, shares own opinion.

I. dotnet Parameters Overview:

. NET, a parameter (formal parameter) variable is part of a method or indexer declaration, and an argument is an expression that is used when a method or indexer is invoked.

In the CLR, all method parameters are passed as values by default. When you pass an object of a reference type, a reference to an object is passed to the method. Here the ship reference itself is passed to the method in the form of a value. This also means that the method can modify the object, and the caller can see the changes. For an instance of a value type, a copy of the instance of the method is passed. means that the method will obtain a copy of the instance of the value type it is dedicated to, and that the instance in the caller is unaffected.

In the CLR, arguments can be passed in a reference rather than a value, and out and ref are used in C # to implement a reference by passing a value. Using out and ref in C # to deliver a value by passing a reference, these two keywords tell the compiler to generate metadata to indicate that the parameter is a reference, and the compiler will generate code to pass the address of the parameter instead of passing the parameter itself. Using out and ref for value types, the effect is equivalent to passing a reference type in a value-passing manner.

Commonly used parameters include basic type parameters, generic parameters, <in t> and <out t>,dynamic, and so on. For example, <in t> and <out T>, which support the variability of generic types in the CLR, C # obtains the syntax necessary for life-generic bianben at 4.0, and now the compiler can also know the possible transformations of interfaces and delegates. Variability is the use of an object as another object in a type-safe manner. Variability is applied to the type parameters of generic interfaces and generic delegates. Covariance is used to return the value of an action to the caller; The contravariant is the caller wants the API to pass in the value; invariance is relative to covariance and contravariance, meaning nothing happens. For this knowledge is very rich, interested in can understand, here will not do a detailed introduction. Dynamic type, C # is a static type of language in which, in some cases, the C # compiler looks for a specific name rather than an interface. Dynamic can do anything at compile time and then be processed by the framework when it is executed. The introduction of dynamic types does not go into more detail.

Parameters in. NET are used mainly for optional parameters, named parameters, variable quantity parameters, and so on. This article is also the main introduction of the three parameters of the use of the method.

Two. dotnet parameter usage:

The following is a description of the usage of three parameters: Optional parameters, named arguments, and passing a variable number of arguments.

1. Optional Parameters:

(1). Basic usage:

Optional arguments are usually available if an operation requires multiple values, and some values are often the same at each call. The ability to implement variable parameters before C # often declares a method that contains all possible parameters, other methods call this method, and pass the appropriate default values.

In an optional parameter, when you design a parameter for a method, you can assign a default value for some or all of the parameters. When you call these method codes, you can choose not to specify a partial argument and accept the default value. You can also pass arguments to a parameter by specifying its name when you call a method. The following example:

  code is as follows copy code
staticvoidoption Alparameters (Intx,inty = 10,intz =)
 {
&NB Sp; console.writeline ("x={0} Y={1} z={2}", x,y,z);
 
optionalparameters (1, 2, 3);
  optionalparameters (1, 2);
  optionalparameters (1);

The above example can be clearly seen in its usage, int y=10 and int z=20 These two parameters are optional parameters. In use of optional parameters, the C # compiler automatically embeds the default value of the parameter if one argument is omitted from the call. When an argument is passed to a method, the compiler evaluated the argument in Left-to-right order. When you pass an argument with a named parameter, the compiler still evaluated the argument in Left-to-right order.

(2). Basic principles:

Optional parameters contain some specifications, some of which require the following:

(a). All optional parameters must appear after the prerequisites, except for the parameter array (declared with the params modifier), but they must appear at the end of the argument list before they are optional arguments.

(b). The parameter array cannot be declared optional, and if the caller does not specify a value, an empty array is used instead.

(c). Optional parameters cannot use ref and out modifiers.

(d). Optional parameters can be of any type, but there are some limitations to the specified default value, that is, the default value must be a constant (numeric 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 default values for methods, constructors, parameters that have parameter properties, and you can specify default values for parameters that are part of a delegate.

(g). C # does not allow omitting the arguments between commas.

When using optional parameters, NULL is used for reference types, and if the parameter type is a value type, only the appropriate nullable value type is used as the default value.

(3). code example:

The code is as follows Copy Code
<summary>
Extract exception and its inner exception stack trace
</summary>
<param name= "Exception" > Exceptions to the Extraction </param>
<param name= "Laststacktrace" > Last fetched stack trace (for recursion), String.Empty or null</param>
<param name= "Excount" > The number of stacks fetched (for recursion) </param>
<returns>Syste.String</returns>
Publicstaticstringextractallstacktrace (thisexception exception,stringlaststacktrace =null,intexCount = 1)
{
while (true)
{
var ex = exception;
Conststringentryformat = "#{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 inner exception
if (ex = ex. innerexception) ==null) Returnlaststacktrace;
exception = ex;
Laststacktrace = $ "{laststacktrace}\r\n\r\n";
Excount = ++excount;
}
}

2. Name the argument:

The above explains some basic concepts and usages of optional parameters, and then take a look at the related operational usage of named parameters:

(1). Basic usage:

A named argument is a parameter name that can be specified at the same time when the value of the argument is specified. The compiler will determine whether the name of the parameter is correct and assign the specified value to the parameter. Named parameters precede each argument with their parameter names and a colon. The following code:

The code is as follows Copy Code
Newstreamwriter (path:filename,aooend:true,encoding:realencoding);

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

The code is as follows Copy Code
Intnumber;
Boolsuccess=int. TryParse ("Ten", Result:outnumber);

(2). Basic principles:

In a named argument, all named arguments must be positioned after the position argument, and the position between the two cannot be changed. A positional argument always points to the corresponding parameter in the method declaration, and cannot be skipped after the argument is specified by naming an argument in the corresponding position. Arguments are still evaluated in the order in which they are written, even if the order may be different from the declaration order of the parameters.

In general, optional parameters are used in conjunction with named Real participants. Optional parameters increase the number of applicable methods, and named real participants reduce the number of methods used. To check for specific applicable methods, the compiler constructs a list of incoming arguments using the order of positional parameters, and then matches the named arguments with the remaining arguments. This method is not applicable if a prerequisite is not specified, or if a named argument cannot match the remaining parameters.

Named arguments can sometimes be substituted for casts to assist the compiler in overload resolution. Changing the default value of a parameter is potentially dangerous if the method is called from outside the module. Arguments can be passed by name to a parameter that does not have a default value, but if the compiler wants to compile the code, all required arguments must be passed.

When writing C # code to interoperate with the COM object model, C # 's optional parameters and named parameter features are best used, and in order to pass an argument by reference, C # also allows you to omit ref/out when you invoke a COM component. Requires that the OUT.REF keyword be applied to the argument.

3. Pass a variable number of parameters:

In project development, sometimes we need to define a method to get a variable number of parameters. You can use Params,params to apply only 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 specific look at the implementation code:

The code is as follows Copy Code
[AttributeUsage (Attributetargets.parameter, Inherited=true, Allowmultiple=false), ComVisible (true), __ Dynamicallyinvokable]
Publicsealedclassparamarrayattribute:attribute
{
Methods
[__dynamicallyinvokable]
Publicparamarrayattribute ();
}
[__dynamicallyinvokable]
Publicparamarrayattribute ()
{
}

The above code can see that the class inherits from the attribute class, which may not be unfamiliar to the attribute class, that is, the base class that defines the custom attribute, stating that the ParamArrayAttribute class is used to define custom attributes. ParamArrayAttribute class under the System namespace, the ParamArrayAttribute class has only one construction method and no concrete implementation. AttributeUsage also defines how properties are used.

When the C # compiler detects a method call, it checks all methods that have the specified name, while the parameter does not apply ParamArrayAttribute. If a matching method is found, the compiler generates the code needed to invoke it. If the compiler does not find a matching method, it will directly check the method that applies the paramarrayattribute. If a matching method is found, the compiler will construct an array of code, populate its elements, and generate code to invoke the selected method.

Calling a method with a variable number of arguments can cause some additional performance damage, the array objects must be allocated on the pair, the array elements must be initialized, and the memory of the array must eventually be garbage collected.

Provides a method code for reference only:

The code is as follows Copy Code
<summary>
Convert a character two-dimensional array into a DataTable
</summary>
<param name= "Stringdyadicarray" ></param>
<param name= "Messageout" ></param>
<param name= "Datatablecolumnsname" ></param>
<returns></returns>
Publicdatatable dyadicarraytodatatable (string[,] stringdyadicarray,outboolmessageout,
Paramsobject[] datatablecolumnsname)
{
if (Stringdyadicarray ==null)
{
Thrownewargumentnullexception ("Stringdyadicarray");
}
var returndatatable =newdatatable ();
if (Datatablecolumnsname.length!= stringdyadicarray.getlength (1))
{
Messageout =false;
returnreturndatatable;
}
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);d yadicarraycolumns++)
{
Adddatarow[datatablecolumnsname[dyadicarraycolumns]. ToString ()] = Stringdyadicarray[dyadicarrayrow, dyadicarraycolumns];
}
RETURNDATATABLE.ROWS.ADD (Adddatarow);
}
Messageout =true;
returnreturndatatable;
}

The above gives a sample using variable parameters and named parameters, completes the conversion of two-dimensional byte array into a DataTable object, traverses the array, and writes the array to the DataTable, the logic of the whole method is not thoroughly introduced, and the code is simpler to compare.

Three. Some of the guiding Principles relating to parameters:

When declaring a parameter type for a method, you should try to specify the weakest type, preferably an interface rather than a base class.

In the basic principles of design pattern, the Dimitri rule is also the least knowledge principle, Dimitri law means that if two classes do not have to communicate with each other directly, then these two classes should not be directly interacting. If one of the classes needs to invoke a method of another class, the call can be forwarded by a third party. In the design of class structures, each class should minimize the access rights of its members. The weaker the coupling between classes, the more beneficial to reuse, a weakly coupled class is modified, does not affect the related classes.

For the use of parameters, we are using the parameter type still need very careful and serious to think, because in the definition of parameter types, to a certain extent, affect the extensibility and stability of our program, if the constraint of the parameter type is relatively large, for the subsequent extension of the method, the significance is enormous. In the whole object-oriented language system, all design patterns are extended by "polymorphism", and the interfaces and delegates are used in our object-oriented design in many ways, and the purpose is to enlarge the constraint of the parameters when using.

In the return value type of a method, the returned type should be declared as the strongest type to avoid being limited to a particular type.

Four. Summary:

The above is a simple introduction to the method parameters of the article, in the content of the article mainly for the introduction of optional parameters, named parameters. The above content if there is a shortage of places also hope that everyone can forgive, also want to be able to point out the corresponding problem. Knowledge before the model, after the reflection. After learning a little, we need to sum up and reflect, the connotation of which we will have the time and energy, as well as the ability to think.

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.