C # basic methods and parameters

Source: Internet
Author: User
Tags finally block

Followed by the previous article "C # basic types and member basics, as well as constants, fields, and attributes"

Instance method and static method

Methods in C # are divided into two types. One belongs to an object (type instance) and the other belongs to the type, it is called a static method (defined by the static keyword ). Everyone is engaged in development, and there is nothing to say about these two.

The only suggestion is: Your static method should be thread-safe (this is easy to start ......).

Constructor (constructor)

Constructor is a special method. The constructor in CLR can be divided into two types: instance constructor and Type constructor. Unlike other methods, the constructor cannot be inherited. Therefore, it is meaningless to apply virtual/new/override/sealed and abstract before the constructor, And the constructor cannot return values.

Instance ConstructorThe initial status of the Instance (that is, the object) used to initialize the type.

For reference types, if we do not explicitly define the instance constructor, the C # compiler will generate a non-parameter instance constructor by default, and this constructor will do nothing, simply call the non-parameter instance constructor of the parent class. We should realize that,If the base class of the class we define does not have a non-argument constructor defined, then our derived class must explicitly call a base class constructor..

     MyBase(

The code above will report the error "MyBase does not contain constructors with 0 Parameters", and a base class constructor must be explicitly called:

     MyBase( MyClass( name) : 

     MyBase()                                     : ( MyBase( name)                          : (name,  MyBase( name,  age)     

In addition to the instance constructor, the C # language also provides a simple syntax for initializing fields, called "inline initialization ":

From the IL code generated after compilation, we can see that inline Initialization is essentially inAllThe instance constructor generates a field to initialize the code. Note that there is a potential code expansion problem here. If we define multiple instance constructors, such initialization code will be generated at the beginning of each instance constructor. This inline initialization should be minimized in the Type Definitions of multiple instance constructors. You can create a constructor to initialize these fields, then let other constructors call the constructor using the this keyword.

For value types, C # does not generate a default no-argument constructor for value types, but CLR always allows Value Type instantiation. That is, for the following value type definition, although we have not defined any constructor, C # does not generate the default no-argument constructor for us, but it can always be instantiated through new (the value type field is initialized to 0 or null ).

     =  MyStruct();    

MyStruct (a) =

MyStruct (a); x =

Type constructor (static constructor)It is used to initialize the initial state of the type, and can only define one and has no parameters. The Type constructor is always private, and C # will automatically mark it as private. In fact, C # prohibits developers from applying any access modifiers to the Type constructor.

When CLR uses a type for the first time, if the Type constructor is defined for this type, CLR calls it in a thread-safe way. We should be aware of the call to the Type constructor. the CLR has to perform a lot of checks and judgments and synchronize threads, so performance will be compromised.

The Type constructor is usually used to initialize static fields in the type. C # also provides an inline initialization syntax:

According to the IL generated by the compiler, the inline initialization of static fields is actually completed in the initialization code generated by the Type constructor, and the first generation is the inline initialization code, then the Code explicitly contained in the Type constructor method is used.

Although the value type can define the Type constructor, never do that.. Because CLR sometimes does not call the Value Type constructor.

Abstract and Virtual Methods

These two concepts are for the inheritance hierarchy of types. If there is no inheritance, they are meaningless. This also means that their accessibility is at least protected, which is visible to the derived class.

Abstract METHODS only define the method name, signature, and return value type, but do not define any method implementation. C # in useAbstractDefinition. The class of the abstract method must be an abstract class. Since an abstract method does not define a method implementation, it is meaningless and must provide the implementation of the method in the derived class (if the derived class is not provided, it must still be defined as an abstract class ).

                Test0() {           Test1() {                      Test3() { 

Used in C #VirtualThe defined method is a virtual method. It seems that there is only one virtual keyword more than defining a common instance method. A virtual method can always be rewritten in a derived class, but cannot be forced. This is the difference between it and an abstract method. You can also logically imagine a virtual method as an abstract method that provides the default implementation. Because the default implementation is provided, it is not mandatory to overwrite a derived class.

After the abstract method is compiled, it is marked as abstract virtual instance (abstract virtual instance method). After the virtual method is compiled, it is marked as virtual instance (virtual instance method ).

Abstract methods and Virtual Methods share the same characteristics. They can be rewritten in a derived class and used in C #.OverrideKeyword to override a method. In VS, if we enter the override keyword and a space in the class, the virtual members (methods, attributes, events, etc.) in all base classes are displayed ). Abstract methods are abstracted and virtual after compilation, so they are displayed in the list.

The overwritten method is still virtual.Of(But not abstract)

The virtual method can be overwritten by a derived class. If you do not want the overwritten method to be overwritten by the next derived class (that is, the class derived from MyClass), you can apply the sealed keyword before override, mark the method as closed.

For example, after I mark Test3 in MyClass as sealed, Test3 is unavailable to the rewritable members listed in VS in the derived class of MyClass.

Of course, you can also apply the sealed keyword to the class, so that the entire class cannot be inherited! Classes cannot be inherited, and all the virtual methods contained in the class are not overwritten.

Partial method (partial keyword)

This is mainly the partial keyword (which can also be applied to classes, structures, and interfaces). You can define a method into multiple files.

There is usually such a scenario: we often use code generation tools to generate some templated code, but some details need to be customized. Although this can be achieved through virtual method rewriting, however, there are two problems:

At this time, we can use the division method. Let the code generator generate a branch class (note that this class can be sealed) and abstract the implementation details into a method definition. As shown below:

                    PrepareSomething( boy,              PrepareSomething(, 

If the implementation of the division method is not provided, the definition of the entire method and all calls to this method will be optimized (Deleted) after compilation, so that the code can be less and faster! This is also because of this (the branch method may not exist after compilation), soThe division method cannot define any modifier or return value.!

Of course, the division method is mainly used to provide implementation details. We can even define this class in different files (enter partial and space in, the implementation of the division method is listed in the current division class ):

                    PrepareSomething( boy, 

Note the following points for the division method:

  • It can only be declared in the branch class or structure.
  • The return type is always void, and the parameter cannot have an out modifier, because this method may not exist after compilation.
  • The division method is always regarded as private. The C # compiler prohibits you from manually specifying any modifier.
Finalize method and Dispose method

These two methods involve the garbage collection part of CLR. Here we will talk about these two methods at the method level. We know that C # Is a hosting language. The program we write is ultimately hosted by CLR, and CLR has a powerful automatic garbage collection mechanism to help us reclaimMemory Resources. However, note that CLR only recycles memory resources automatically. In addition to memory resources, other system resources (such as files, network connections, sockets, and mutex) need to be used. Therefore, CLR provides a mechanism to release these resources, this is the Finalize method (Terminator ).

The Finalilze method here does not mean to define a Finalize method directly in the class (although it can be defined, it will never be done !), It refers to a method defined by the destructor, that is,"~ Class Name ()". After the method is compiled, a method named Finalize is generated. The CLR calls the Finalize method to release some resources before deciding to recycle objects containing the Finalize method (this specific process will be written to the CLR garbage collection part later ).

It briefly demonstrates how to define a Terminator. We define a method by defining the Destructor syntax (note that this method has no parameters or any modifiers). After compilation, the compiler generates a protected virtual method named Finalize for us. In addition, a try block is generated inside the method to wrap the code in the original method, and a finally block is generated to call the Finalize method of the base class.

Although the Finalize method syntax is the same as the C ++ destructor syntax, the principles of the two are still completely different in the CLR book, therefore, it cannot be called a destructor (in my understanding, the destructor in C ++ should release the resources used by the object, including memory resources, and the object will be cleaned up after the call; the Finalize method in C # Only releases the system resources used by the object, and the object remains alive after the call until the CLR recycles it. I don't know if this is correct. Please give me some advice !).

Although the Finalize method is useful, it can release some resources. Note that the call is determined by CLR, so the call time cannot be guaranteed. Therefore, we need a mechanism to explicitly release resources, which isDisposeMode.. Net provides the IDisposable interface (including the only Dispose method). If we implement this interface, it means that our class implements the Dispose mode. In the Dispose method, we disable the system resources used by the object. In this way, we can explicitly call the Dispose method in the code to release resources, instead of passively giving them to the CLR for release. In CLR Via C #,We recommend that all classes that implement the terminator implement the Dispose mode at the same time.. The following class implements the Terminator and the Dispose mode (no matter whether the implementation details are reasonable ):

            =         ~MyFinalization()        {            mutex =           Dispose()        {            mutex = 

After using the MyResource object, you can call the Dispose method to release the resource.

    MyResource resource =          resource.Dispose(); 

For the types that implement the Dispose mode, C # also provides the using statement to simplify our encoding.

     (MyResource resource =             }

    MyResource resource =          (resource != 
Extension Method

The extension method enables us to "add" methods to existing types without creating new derived types, re-compiling, or modifying original types in other ways. An extension method is a special static method, but it can be called like an instance method of the extension type, at the same time, it can be well supported by VS smart prompts (we can point out the extension method just like using the object instance method ).

Defining an extension method has the following requirements:

  • It must be defined in a non-generic static class (the class name does not matter ). This class must be a top-level class, that is, it cannot be nested in other classes.
  • The extension method must be a static method.
  • The first parameter must specify the extended type and be identified by the this keyword.
      ExtensionMethods      IsNullOrEmpty(  s)      

     name =     name.IsNullOrEmpty();   

Pay attention to the following points about the extension method:

  • C # only supports extension methods, but does not support extension attributes, Extension events, extension operators, and so on (although they are essentially methods ).
  • Before using the extension method, you must first introduce the namespace of the class where the extension method is located.
  • Multiple Static classes can define the same extension method. In case of a conflict, you can only call the extension method by calling the static method syntax.
  • Extension methods can be inherited. If we extend a type, all its derived types can call this extension method.
  • Potential version problems. If Microsoft adds a method of the same name as your extension method in the type in the future, all calls to the extension method will become to call Microsoft's method.

Extended Methods: crane chongtian Http://www.cnblogs.com/ldp615/archive/2009/08/07/1541404.html

Value Type parameters and reference type parameters

Passing parameters is a value assignment operation. We can regard the method parameters as some variables defined by the method. Passing parameters is the process of assigning values to these variables. The value assignment process is the process of copying the thread stack content. The value stack content stores the value instance itself, and the reference stack content stores the address of the referenced instance on the stack. The differences here are mainly the differences between the value type and the memory allocation of the reference type. For details, refer to C # basic types. Therefore, after passing parameters, the value type parameter of the method has the copy of the original value (one copy), and the changes to the parameter do not affect the original value, because they are not a piece of memory at all! Parameters of the reference type of the method have the same address as the original value. They point to the same heap memory. Therefore, changes to parameters of the reference type affect the original value. The following example defines a value type val and a reference type refObj respectively. After the Work method is called, The Value Type val is not modified, and the reference type refObj is modified.

     Main(=  val = =  RefType { Id = , Name =       Id { ;   Name { ;           Work(++++= b.Name + 
Optional and named Parameters

After we define a method with many parameters, we need to prepare these parameters for all calls to call this method. However, in some cases, we only care about some of the parameters when calling them. We usually define several methods with few parameters through overloading, call the method with the most parameters after completing other parameters. However, this is purely physical and cannot overload all possible parameter combinations. Therefore, C # provides a mechanism to specify the default value for the parameter while defining the method. In this way, if no value is provided for the parameter in the method call, the default value is used, parameters with default values are optional.

          ToUpperOrLower( message,  isToUpper = ,  other =  (isToUpper)  

         result = dw.ToUpperOrLower();

Parameter Name: Parameter Value"Syntax to provide a value for the parameter. This syntax requires that the parameter matching method should not be in the Parameter order, but based on the provided name. As shown in the following figure (parameters that do not use the naming parameter syntax still match in the Parameter order, for example, the first parameter "Heku "):

         result = dw.ToUpperOrLower(, other: );

When defining method parameters, pay attention to the following points:

  • You can specify default values for parameters with parameter properties, methods, constructors, and parameters in the delegate definition.
  • Parameters with default values must be placed behind those without default values.
  • The default value must be a constant value that can be determined during compilation.
  • Do not rename parameter variables. For example, if the third parameter is renamed in the ToUpperOrLower method above, an error is returned because the other parameter cannot be found in the call.
  • If the parameter is identified by the ref or out keyword, the default value cannot be set.
Variable number of parameters (params keyword)

If we want to design a method to calculate the sum of all input numbers. As we have done in the past (do not pay attention to the internal implementation of the method ):

                  sum( sum =  ( item +=

Because the number of numbers entered is unknown, an array is used to receive these numbers. During the call, We have to initialize an array before calling the method. To simplify this programming method, you can apply the params keyword before defining the numbers parameter.

                  sum(  sum =  ( item +=

        sum(, , );

        [] numbers =  [] { , , 

For variable parameters, pay attention to the following points:

  • The Params keyword can only be applied to the last parameter in the method signature.
  • This parameter must be a one-dimensional array!
  • When calling a method with the params keyword, there will be extra performance loss (unless null is explicitly passed ). Because the array object must be allocated on the heap, the array element must be initialized, And the Array Memory must eventually be recycled. To reduce performance loss, you can define several overloaded versions that do not have the params keyword. For example, the Format method is defined in System. String:

PASS Parameters by reference (ref and out keywords)

By default, all method parameters in CLR are passed values (the content of the thread stack), but this default method can be changed by applying the ref or out keyword to the parameters. The only difference between the two keywords is that the parameters marked with ref must be initialized before being passed, but those marked with out are not required.

When passing a parameter that applies the ref or out keyword,It refers to the reference (address) of the thread stack content)Note that this is not the heap address (Passing parameters in reference mode does not mean converting parameters into reference types for passing). The following is an example:

          Update(  a,   b)        {            a++= 

A method is defined above to receive a value type parameter and a reference type parameter. The parameter must be passed as a reference (with the ref keyword added ). Call the following:

         a =  o =   c =        Update( a,        Console.WriteLine(a);        Console.WriteLine(o == == );

View Code

End

Another weekend, I finally completed the summary of the nature of this reading note. The section "operator overload methods and conversion Operator Methods" in the outline listed by myself has not been written in because I have not learned much about it too much (I will have a chance to fill it in later ).

Fellow park friends, Ben Si is also a cainiao in learning. If I understand some knowledge points incorrectly, please point it out! Thank you!

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.