Approaching will be near, the whole person has no work and writing passion, estimated this time a lot of people with me, the Blind date, the party drinking the party drinking, in short, there is no work of mind (I have a lot of ideas, but is called not to move my hands and feet, so I can only see others doing what I want to do, eat what I want to eat. )。 I from last month, four or five weekly, to the current article shortened to a weekly article, to tell the truth, now an article also has not wanted to write the mind (this piece or bite tooth write, feel really is write not move, write blog too toss people, who write who know Ah! ), but still hope to write to help everyone, such as the lack of writing, but also hope that we are more correct, knowledge is summed up and reflect on others also on their own is an improvement.
Here first a piece of nonsense, to ease the atmosphere, so that everyone is very embarrassed (too direct or not too good, can not see the girls like to vindicate it, but also to get along, let people think you have a steady depth. ), now into our blog content today, that is. NET's parameter usage. Because in. NET parameter usage and constraints are particularly large, for many beginners, such a large number of parameter users is just like the drag, even for the rich experience of the developer, it is not easy to use all the parameters and choose the appropriate parameter type. When it comes to parameters, it is estimated that many people just think of the way we use in the general method call, such as string,int,object and so on type, more also have no impression, is to know, that is, in the encounter and then go to look at, this is actually true, After all, can not spend too much time on what is not commonly used knowledge, but I personally think that knowledge or need to have a comprehensive study in advance, may be specific details can not be very good grasp, but for the overall concept still have to have a whole study.
Here is a brief introduction. NET some commonly used parameter usage, if have insufficient also to correct, also welcome everybody in the following message discussion, share own opinion.
I. dotnet Parameters Overview:
. NET parameter (formal parameter) variables are part of a method or indexer declaration, and an argument is an expression that is used when a method or indexer is called.
In the CLR, all method parameters are passed by default. When you pass an object of a reference type, a reference to an object is passed to the method. The ship's reference itself is passed to the method in the form of a passing 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, pass a copy of the instance to the method. means that the method will get a copy of the instance of the value type it is dedicated to, and the instance in the caller is unaffected.
In the CLR, arguments are passed in a way that passes a reference rather than a value, and in C # uses out and ref to pass the value in the way that the reference is passed. Using out and ref in C # to implement the passing of a reference, the two keywords tell the compiler to generate metadata to indicate that the parameter is referenced, and the compiler generates code to pass the address of the parameter instead of passing the parameter itself. Using out and ref for value types is equivalent to passing a reference type in a value-pass manner.
Common 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 knows the possible transformations of interfaces and delegates. Variability is the use of one object as another object in a type-safe manner. The variability is applied to the generic interface and the type parameters of the generic delegate. Covariance is used to return the value of an operation to the caller; contravariance refers to the caller who wants the API to pass in a value; invariance is relative to covariance and contravariance, which means nothing happens. For this aspect of knowledge is very rich, interested can self-understanding, here do not do a detailed introduction. The dynamic type, C # is a statically typed language, and in some cases the C # compiler looks for a specific name instead of 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 is not a more in-depth introduction.
The use of parameters in. NET is mainly optional parameters, named parameters, variable quantity parameters, and so on. The following is also the main introduction of the three kinds of parameters of the use of methods.
Two. dotnet parameter usage:
The following is a main introduction to the use of three parameters: Optional parameters; name arguments; pass a variable number of arguments.
1. Optional Parameters:
(1). Basic usage:
If an operation requires more than one value, and some values are often the same at each invocation, an optional parameter can usually be used. The ability to implement mutable parameters before C # often declares a method that contains all possible parameters, other methods call the 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 calling these method codes, you can choose not to specify partial arguments and accept the default values. You can also pass an argument to a method when it is called by specifying the name of the parameter. The following example:
void Optionalparameters{Console.WriteLine ("x={0} Y={1} z={2}", X, Y, Z); } optionalparameters (3); Optionalparameters (2); Optionalparameters (1);
The above example can clearly see its usage, the two parameters of int y=10 and int z=20 are optional parameters. In the use of optional parameters, if a parameter is omitted when called, the C # compiler automatically embeds the default value of the parameter. When you pass an argument to a method, the compiler evaluates the argument in a left-to-right order. When you pass an argument with a named parameter, the compiler still evaluates the argument in left-to-right order.
(2). Basic principles:
The optional parameters contain some specifications, some of which are as follows:
(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 parameter list, before they are optional.
(b). The parameter array cannot be declared optional, and an empty array will be used instead if the caller does not specify a value.
(c). Optional parameters cannot use the ref and out modifiers.
(d). Optional parameters can be of any type, but there are limits to the specified default value, which is that the default 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 the conversion cannot be user-defined.
(f). You can specify a default value for a method, a constructor, an argument-parameter property, and a default value for a parameter that is part of a delegate.
(g). C # does not allow arguments between commas to be omitted.
When using an optional parameter, NULL is used for the reference type to make the default value, and if the parameter type is a value type, only the corresponding nullable value type is used as the default value.
(3). code example:
///<summary>///Extracting exceptions and their internal exception stack traces///</summary>///<param name= "Exception" >Exceptions for Extraction</param>///<param name= "Laststacktrace" >Last extracted stack trace (for recursion), String.Empty or null</param>///<param name= "Excount" >Number of stacks fetched (for recursion)</param>///<returns>Syste.string</returns>PublicStaticString Extractallstacktrace (This Exception Exception,String laststacktrace =Nullint excount =1) {while (True) {var ex =exceptionConstString 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]} ");} // recursive add inner exception if (ex = ex. innerexception) = = null) return Laststacktrace; exception = ex; laststacktrace = $ "{laststacktrace}\r\n\r\n" Span style= "COLOR: #000000" >; Excount = ++excount;}}
2. Name the arguments:
This explains some of the 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 refers to a parameter name that can be specified at the same time as the value of the specified argument. The compiler will determine if the name of the parameter is correct, and assign the specified value to the parameter. Named arguments precede the individual arguments with their parameter names and a colon. 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 place the ref and out modifier before the argument, after the name.
int number ; BOOL success=Int. TryParse ("ten", Result: Out number);
(2). Basic principles:
In a named parameter, all named arguments must be located after the positional arguments, and the position between them cannot be changed. A positional argument is always pointed to the corresponding parameter in the method declaration, and cannot be skipped after the argument is specified by naming an argument at the appropriate location. The arguments are still evaluated in the order in which they are written, even if the order may be different from the argument's declaration order.
In general, optional parameters are used in conjunction with named Real attendees. The optional parameters increase the number of methods that are applied, and the names are reduced by 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 parameters. This method is not applicable if you do not specify a prerequisite parameter, or if a named argument cannot match the remaining parameters.
Named arguments can sometimes be used in place of casts to assist the compiler in overloading decisions. If the method is called from outside the module, changing the default value of the parameter is potentially dangerous. Arguments can be passed by name to parameters that do not have a default value, but if the compiler wants to compile the code, all required arguments must be passed.
C # 's optional and named parameter functionality is best used when writing C # code to interoperate with the COM object model, where a COM component is invoked to pass an argument in the form of a reference, and C # also allows for omitting ref/out, which, when used with COM components, C # 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 a method signature. The params keyword tells the compiler to apply an instance of System.paramarrayattribute to the parameter. Let's take a look at the implementation code:
[AttributeUsage (Attributetargets.parameter, inherited=true, allowmultiple=false), ComVisible (true ), __dynamicallyinvokable]class// Methodspublic paramarrayattribute ();} [__dynamicallyinvokable] public
The above code can see that the class inherits from the attribute class, and for the attribute class, it may not be unfamiliar, that is, the base class for defining custom properties, stating that the ParamArrayAttribute class is used to define custom properties, ParamArrayAttribute class under the System namespace, the ParamArrayAttribute class has only one construction method and no specific implementation. AttributeUsage also defines how properties are used.
When a method call is detected by the C # compiler, all methods that have the specified name and no ParamArrayAttribute applied are checked. If a matching method is found, the compiler generates the code needed to call it. If the compiler does not find a matching method, the method of applying ParamArrayAttribute is checked directly. If a matching method is found, the compiler will construct an array, populate its elements, and then generate code to invoke the selected method.
When calling a method with a variable number of arguments, there are some additional performance losses, the array object must be allocated on the pair, the array element must be initialized, and the memory of the array must eventually be garbage collected.
Provides a method code for reference only:
///<summary>///Converting a two-dimensional character array into a DataTable///</summary>///<param name= "Stringdyadicarray" ></param>///<param name= "Messageout" ></param>///<param name= "Datatablecolumnsname" ></param>///<returns></returns>Public DataTable dyadicarraytodatatable (string[,] Stringdyadicarray,OutboolMessageout,ParamsObject[] datatablecolumnsname) {if (Stringdyadicarray = =Null) {ThrowNew ArgumentNullException ("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 (stringdyadicarray[dyadicarrayrow, Dyadicarraycolumns];} RETURNDATATABLE.ROWS.ADD (Adddatarow); } messageout = true; return returndatatable;}
The above gives a sample of the use of variable parameters and named parameters, completed the conversion of a two-dimensional byte array into a DataTable object, the array is traversed, and the array is written to the DataTable, for the entire method of the logic is not done in-depth introduction, the code comparison is simple.
Three. Some of the Guiding Principles related to parameters:
When declaring a method's parameter type, you should try to specify the weakest type, preferably an interface rather than a base class.
In the basic principles of design patterns, the Dimitri law is also the least knowledge principle, and the Dimitri rule is that if two classes do not have to communicate directly with each other, then these two classes should not interact directly. If one of the classes needs to invoke a method of another class, the call can be forwarded through a third party. In the design of a class structure, each class should minimize the access rights of members. The weaker the coupling between classes, the more beneficial it is to reuse, and a class that is in a weak coupling is modified without affecting the related classes.
For the use of parameters, we still need to be very careful and serious in the use of parameter types, because in the definition of parameter types, to a certain extent, affect the extensibility and stability of our program, if the constraints of the parameter type is relatively large, for the extension of subsequent methods, the significance is enormous. In the whole object-oriented language system, all the design patterns are extended by "polymorphic", for interfaces and delegates are used in our object-oriented design, many purposes are to expand the constraints of the parameters when used.
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 of the method parameters of the article, in the article content mainly for the introduction of optional parameters, named parameters and so on. If there are deficiencies in the above content, we also hope that we can forgive, but also want to point out the corresponding problems. Knowledge precedes model, then reflection. After learning a little, we need to summarize and reflect on the connotation of which we will have time and energy, as well as by the ability to think.
About. The thinking of net parameter passing way