In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how the .NET parameters are passed, and the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.
1. Overview of DotNet parameters:
In .NET, a parameter (formal parameter) variable is part of a method or indexer declaration, and an argument is an expression used when calling a method or indexer.
In CLR, all method parameters are passed values by default. When you pass an object of a reference type, a reference to an object is passed to the method. The ship reference itself here is passed to the method by passing 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, pass a copy of the instance of the method. Means that the method will get a copy of its dedicated instance of the value type, and the instance in the caller will not be affected.
Parameters are allowed to be passed by reference instead of value in CLR, and values are passed by passing references in C # using out and ref. In C #, out and ref are used to pass values by passing references. These two keywords tell the compiler to generate metadata to indicate that the parameter is referenced, 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 is equivalent to passing reference types by passing values.
The commonly used parameters are basic type parameters, generic parameters, and, dynamic, and so on. For example, and support the variability of generic types in CLR, C # acquired the necessary syntax for a life-long generic body at 4.0, and now the compiler is able to know the possible conversions of interfaces and delegates. Variability is about using one object as another in a type-safe way. Variability is applied to type parameters of generic interfaces and generic delegates. Covariant is used to return the value of an operation to the caller; inverse means that the caller wants to API the value; and invariance is relative to covariance and inverse variability, which means that nothing happens. The knowledge in this area is very rich, and those who are interested can understand it by themselves, so I won't introduce it in detail here. Dynamic type, C # is a statically typed language, and in some cases, the C # compiler is looking for a specific name rather than an interface. Dynamic can do anything at compile time, and then be handled by the framework at execution time. There is no more in-depth introduction to dynamic types.
The main ways to use parameters in .NET are optional parameters, named parameters, variable number parameters, and so on. The following part of this article mainly introduces the use of these three parameters.
II. Usage of DotNet parameters:
The following mainly introduces the use of three kinds of parameters: optional parameters, named arguments, and passing a variable number of parameters.
1. Optional parameters:
(1)。 Basic usage:
If an operation requires multiple values, and some values tend to be the same each time they are called, you can usually use optional parameters. Implementing the function of variable parameters before C # often declares a method that contains all possible parameters, and other methods call this method and pass the appropriate default values.
Among the optional parameters, when designing the parameters of a method, you can assign default values to some or all of the parameters. When calling these methods, the code can choose not to specify some arguments and accept the default values. You can also pass arguments to a method by specifying a parameter name when you call it. The following is an example:
Static void OptionalParameters (int x, int y = 10, int z = 20) {Console.WriteLine ("x = {0} y = {1} z = {2}", x recorder y paper z);} OptionalParameters (1,2,3); OptionalParameters (1,2); OptionalParameters (1)
The usage of the above example can be clearly seen, and the two parameters int yearly 10 and int zonal 20 are optional parameters. In the use of optional parameters, if a parameter is omitted during the call, the C# compiler automatically embeds the default value of the parameter. When you pass arguments to a method, the compiler evaluates the arguments from left to right. When you pass arguments using named parameters, the compiler still evaluates the arguments from left to right.
(2)。 Basic principles:
Optional parameters include some specifications, some of which are as follows:
(a). All optional parameters must appear after the required parameters, except for the parameter array (declared with the params modifier), but they must appear at the end of the parameter list, and before them are optional parameters.
(B). Parameter arrays cannot be declared optional, and if the caller does not specify a value, an empty array will be used instead.
(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 default value specified, that is, the default value must be constant (numeric or string literals, null, const members, enumeration members, default (T) operators).
(e). The specified value is implicitly converted to a parameter type, but the conversion cannot be user-defined.
(F). You can specify default values for methods, constructors, parameters with parameter properties, and for parameters that are part of a delegate.
(G) .C # does not allow arguments between commas to be omitted.
When using optional parameters, use null as the default value for reference types, and if the parameter type is a value type, you only need to use the corresponding nullable value type as the default value.
(3)。 Code example:
/ extract exception and its internal exception stack trace / exception extracted / last extracted stack trace (for recursion), String.Empty or null / number of stacks extracted (for recursion) / Syste.String public static string ExtractAllStackTrace (this Exception exception, string lastStackTrace = null, int exCount = 1) {while (true) {var ex = exception 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\ nData:"; lastStackTrace = exception.Data.Cast () .Aggregate (lastStackTrace, (current, entry) = > current + $"\ r\ n\ t {entry.Key}: {exception.Data [entry.Key]}") } / / Recursive add internal exception if ((ex = ex.InnerException) = = null) return lastStackTrace; exception = ex; lastStackTrace = $"{lastStackTrace}\ r\ n\ r\ n"; exCount = + + exCount;}}
two。 Named argument:
The above explains some basic concepts and usage of optional parameters, and then take a look at the relevant operational usage of named parameters:
(1)。 Basic usage:
Named argument means that when you specify the value of the argument, you can specify the corresponding parameter name at the same time. The compiler determines whether the name of the parameter is correct and assigns the specified value to the parameter. Named parameters precede individual arguments with their parameter names and a colon. The code is as follows:
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 argument.
Int number;bool success=int.TryParse ("10", result:out number)
(2)。 Basic principles:
In named parameters, all named parameters must be located after the location argument, and the position between the two cannot be changed. The positional argument always points to the corresponding parameter in the method declaration and cannot be specified by naming the argument at the corresponding location after skipping the parameter. Arguments are still evaluated in the order in which they are written, even though this order may be different from the order in which parameters are declared.
In general, optional parameters are used in conjunction with named arguments. Optional parameters increase the number of applicable methods, while named arguments reduce the number of methods used. To check whether there is a specific applicable method, the compiler builds 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 a required parameter is not specified, or if a named argument cannot match the remaining parameters.
Named arguments can sometimes be used instead of casting to assist the compiler in overloading decisions. It is potentially dangerous to change the default value of a parameter if the method is called from outside the module. You can pass arguments by name to parameters that have no default values, but in order for the compiler to compile the code, all required arguments must be passed.
When writing C # code to interoperate with the COM object model, the optional and named parameters of C # are best used. When calling a COM component, in order to pass an argument by passing a reference, C # also allows REF/OUT to be omitted. When using COM components, C # requires that the OUT.REF keyword must 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 only to apply to the last parameter in the method signature. The params keyword tells the compiler an instance of applying System.ParamArrayAttribute to a parameter. Let's take a look at the code for the implementation:
[AttributeUsage (AttributeTargets.Parameter, Inherited=true, AllowMultiple=false), ComVisible (true), _ _ DynamicallyInvokable] public sealed class ParamArrayAttribute: Attribute {/ / Methods [_ DynamicallyInvokable] public ParamArrayAttribute ();} [_ DynamicallyInvokable] public ParamArrayAttribute () {}
The above code can see that this class inherits from the Attribute class, and it may be no stranger to the Attribute class, that is, the base class that defines custom attributes, indicating that the ParamArrayAttribute class is used to define custom attributes, and the ParamArrayAttribute class has only one constructor and no specific implementation under the System namespace. AttributeUsage also defines how attributes are used.
When the C # compiler detects a method call, it checks all methods with the specified name and parameters that do not have a ParamArrayAttribute applied. 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 directly checks the method that applies ParamArrayAttribute. If a matching method is found, the compiler will construct an array into code, populate its elements, and then generate code to call the selected method.
When calling a method with a variable number of parameters, there is some additional performance loss, the array objects must be allocated on the pair, the array elements must be initialized, and the array memory must eventually be garbage collected.
Provides a method code for reference only:
/ character 2D array converted to DataTable / public DataTable DyadicArrayToDataTable (string [,] stringDyadicArray, out bool messageOut, params object [] dataTableColumnsName) {if (stringDyadicArray = = null) {throw new ArgumentNullException ("stringDyadicArray");} var returnDataTable = new DataTable (); if (dataTableColumnsName.Length! = stringDyadicArray.GetLength (1)) {messageOut = false; return returnDataTable } for (var dataTableColumnsCount = 0transferdataTableColumnsCount < 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.ToString ()] = stringDyadicArray [dyadicArrayRow, dyadicArrayColumns] } returnDataTable.Rows.Add (addDataRow);} messageOut = true; return returnDataTable;}
The above gives an example of using a variable number of parameters and named parameters, and completes the conversion of a two-dimensional byte array into a DataTable object, traverses the array, and writes the array into datatable. The logic of the whole method is not introduced in depth, and the code is simple.
three。 Some guidelines related to parameters:
When declaring the parameter type of a method, you should try to specify the weakest type, preferably an interface rather than a base class.
Among the basic principles of the design pattern, the Demeter rule is also the least knowledge principle, which means that if two classes do not have to communicate directly with each other, then the two classes should not directly interact with each other. If one of the classes needs to call a method of another class, the call can be forwarded through a third party. In the design of class structure, each class should minimize the access rights of its members. The weaker the coupling between classes, the more conducive to reuse, a class in weak coupling is modified, will not affect the related classes.
In the use of parameters, we still need to think carefully about the use of parameter types, because the definition of parameter types affects the expansibility and stability of our program to a certain extent. if the constraint of the parameter type is relatively large, it is of great significance for the expansion of the follow-up method. In the whole object-oriented language system, all design patterns are extended from "polymorphism". Interfaces and delegates are often used in our object-oriented design, and the purpose is to expand the constraint of parameters.
In the return value type of a method, the returned type should be declared as the strongest type so as not to be limited by a specific type.
On the way of .NET parameter transmission is shared here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.