CLR via C # Note 4,

Source: Internet
Author: User

CLR via C # Note 4,
Instance constructor and class (reference type)Constructor is a special method that allows you to initialize a type of instance to a good state. The constructor method is always called. ctor in "method definition metadata table. When creating an instance of the reference type: #1, first allocate memory for the instance's data fields #2, then initialize the additional fields of the object (type object pointer and synchronous block index) #3, finally, when the instance constructor of the type is called to set the initial state of the object to construct the object of the reference type, the memory allocated to the object is always first cleared before the instance constructor of the type is called. The constructor does not display a value of 0 or null for all overwritten fields. Unlike other methods, the instance constructor cannot be inherited. If the base class does not provide a non-argument constructor, the derived class must explicitly call a base class constructor. Otherwise, the compiler reports an error. If the class modifier is static (sealed and abstract-static classes are abstract and sealed Classes in metadata), the compiler will not generate a default constructor in the class definition. Note: Before calling the constructor of the base class, the compiler initializes any fields that use the simplified syntax to maintain the "these fields are always a value" impression of the source code.Instance constructor and structure (value type)The struct constructor works in a different way than the referenced class constructor. CLR always allows creation of value-type instances, so there is no way to prevent value-type instantiation. The type definition has no parameter constructor, but CLR permits it. To improve the runtime performance of the application, the C # compiler does not automatically generate such code (automatically calls the value-type parameter-free constructor, even if the value type provides a parameter-free constructor ). Therefore, the value type does not need to define the constructor. The C # compiler does not generate a default no-argument constructor for the value type at all. CLR does allow defining constructors for value types and must be called explicitly, even if there is no argument Constructor (to enhance application performance ). In fact, the C # compiler is not allowed.Type constructorCLR also supports Type constructor, also known as static constructor, class constructor, or type initializer ). The Type constructor can be applied to interfaces (not allowed by the C # compiler), reference types, and value types. #1. The instance constructor is used to set the initial status of a type of instance. Correspondingly, the Type constructor is used to set the initial state of the type. By default, no Type constructor is defined. If it is defined, only one parameter can be defined and there will never be any parameter. #2. The Type constructor does not allow access modifiers. In fact, it is always private, and the C # compiler will automatically mark it as private. The reason for being private is to prevent any code written by developers from calling it, And the CLR is always responsible for calling it. #3. Calling the Type constructor is troublesome. When compiling a method, the JIT compiler will view the types referenced in the code. If any type defines the Type constructor, the JIT compiler will check whether the Type constructor has been executed for the current AppDomain. If the constructor has never been executed, the JIT compiler adds a call to the Type constructor in its native code. If the Type constructor has been executed, the JIT compiler does not add a call to it because it knows that the type has been initialized. #4. After the method is compiled by the JIT compiler, the thread starts to execute it and finally runs the code of the called Type constructor. Multiple Threads may execute the same method at the same time. The CLR wants to ensure that one Type constructor can only be executed once in each AppDomain. To ensure this, the calling thread needs to obtain a mutex thread synchronization lock when calling the Type constructor. In this way, if multiple thread views call a static Type constructor of a certain type at the same time, only one thread can obtain the lock, and other threads will be blocked ). The first thread executes the code in the static constructor. When the first thread leaves the constructor, the waiting thread is awakened and the constructor code has been executed. #5. Although a Type constructor can be defined in the value type, never do so because CLR sometimes does not call the static Type constructor of the value type. #6. CLR ensures that a Type constructor is executed only once in each AppDomain, and (such execution) is thread-safe, therefore, it is very suitable for initializing any singleton object required by the Type constructor. Finally, if the Type constructor throws an unprocessed exception, the CLR considers this type unavailable. Attempting to access any field or method of this type will throw a System. TypeInitializationException. The code in the Type constructor can only access static fields of the type, and its general purpose is to initialize these fields. Like instance fields, C # provides a simple syntax to initialize static fields of the type.Operator overload methodSome programming languages allow an instance of the type definition operator to operate on the type. For example, many types (System. String) overload equal (=) and unequal (! =) Operator. CLR does not know anything about Operator overloading. They even do not know anything about operators. The Programming Language defines the meaning of each operator and what code should be generated when these special symbols appear. Public sealed class Complex {public static Complex operator + (Complex c1, Complex c2 ){...}} interoperability between operators and programming languages: if a type defines an operator overload method, Microsoft also recommends that the type define a more friendly public static method and call the operator overload method within the method. The System. Decimal type of FCL demonstrates how to overload operators and define friendly method names according to Microsoft's knowledge principles.Conversion Operator MethodSometimes you need to convert an object from a type to a different type. For example, you sometimes have to convert the Byte type to Int32. In fact, when both the source and target types are compiler primitive types, the compiler knows how to generate the Code required for the conversion object. Some programming languages (such as C #) provide overloading of conversion operators. The conversion operator is a method that converts an object from one type to another. You can use special syntax to define the conversion operator method. The CLR specification requires that the conversion operator overload methods must be public and static. In addition, C # requires that the parameter type and return type must be the same as the type of the definition conversion method. Similarly, in C #, the implicit keyword tells the compiler that explicit transformation is not required in the source code to generate code to call methods. On the contrary, the explicit keyword tells the compiler to call a method only when explicit transformation is discovered. After the implicit or explicit keyword, specify the operator keyword to tell the compiler that the method is a conversion operator. After operator, specify the type of the object to be converted. Within parentheses, it specifies the type of conversion from.Extension Method Application Extension Method: C # only supports extension methods. Extension methods such as extension attributes, Extension events, and extension operations are not supported (this method is available before the first parameter) it must be declared in a non-generic static class. However, there is no restriction on the class name. Of course, the extension method must have at least one parameter, and only the first parameter can be marked with the this keyword. C # When the compiler looks for extension methods defined in static classes, these static classes must have file scopes. Extension methods also extend the derived types. Therefore, the System. object is used as the first parameter of the extension method. Otherwise, this method can be called on all expression types, resulting in too much junk information filled in the "smart sensing" Window of Visual Studio. There are potential version control problems with the extension method. Extension Method. You can also define extension methods for interface types. The extension method is the foundation of Microsoft's Language Integrated Query (Language Integrated Query) technology. C # The Compiler allows you to create a delegate to reference extension methods on an object. Action a = "Jeff". ShowItems; ();Division MethodThe return type of the partial method can only be declared in the partial class or structure is always void, and no parameter can be marked with an out modifier. Because the method may not exist at runtime, initializing a variable as a method may return something. There can be ref parameters, generic methods, instances, or static methods. If there is no corresponding implementation part, you cannot create a delegate in the code to reference this partial method. The division method is always regarded as a private method. Bytes ----------------------------------------------------------------------------------------------------Parameters Optional and named ParametersWhen you design parameters for a method, you can assign default values to some or all parameters.PASS Parameters to methods by referenceBy default, CLR assumes that all method parameters are passed values. When an object of the reference type is passed, the reference to an object (or a pointer to the object) will be passed to the method. Note that this reference (or pointer) is passed to the method by passing values. This means that the method can modify the object, and the caller can see these changes. When a value-type instance is passed, a copy of the instance is passed to the method, which means that the method obtains a copy of a dedicated value-type instance, and the caller's instance is not affected.Keyword out or refIn C #, parameters can be passed by referencing instead of passing values. This is done using the keyword out or ref, telling the C # compiler to generate metadata to indicate that this parameter is referenced. The compiler will also generate code to pass the parameter address, instead of passing the parameter itself. The caller must allocate memory for the instance, and the caller can manipulate the memory (content ). From the CLR perspective, the keyword out and ref are exactly the same. This means that no matter which keyword is used, the same IL code will be generated. The metadata is almost the same, except for only one bit. It is used to record whether to specify out or ref when declaring a method. C # The Compiler treats the two keywords differently, and the difference determines which method is responsible for initializing the referenced object. If the method parameters are marked with out, it indicates that the caller is not expected to initialize the object before calling the method, and the value must be written to the value before the return. If it is marked by ref, the caller must initialize the parameter value before calling this method. The called method can read the value and/or write it to the value. To sum up, from the perspective of IL and CLR, The out and ref are the same thing: both lead to a pointer to the instance being passed. But from the compiler perspective, the compiler will verify that the code you write is correct according to different standards (requirements.Important:If there is only a difference between out and ref between the two overload methods, it is invalid because the metadata representation of the two signatures is identical. For a variable (real parameter) that is passed to the method by reference, its type must be the same as the type (form parameter) declared in the method signature.Know the principles of parameters and return types #1. Specify the weakest type when declaring the parameter type of a method, preferably an interface rather than a base class. For example, if you want to write a method to process a set of data items, it is best to use an interface (such as IEnumerable <T> to declare the parameters of the method ), do not use strong data types (such as List <T>) or stronger interface types (such as ICollection <T> or IList <T> ). // public void AddItems <T> (IEnumerable <T> collection ){...} // poor public void AddItems <T> (List <T> collection ){...} if you need a list (not just an enumerated object), you should declare the parameter type as IList <T>. However, do not declare the parameter type as List <T>. The example here is a set, which is designed using an interface architecture. The concept also applies to classes designed using the basic class architecture. For example: // public void ProcessBytes (Stream someStream ){...} // public void ProcessBytes (FileStream fileStream ){...} the first method can process any stream, including FileStream, NetworkStream, and MemoryStream. The second method can only process FileStream, which limits its applications. #2. Generally, the return type of the method is declared as the strongest type (to avoid being limited to a specific type ). For example, it is better to declare a method to return a FileStream object instead of a Stream object. // Public FileStream OpenFile (){...} // public Stream OpenFile (){...} if a method returns a List <String> object, you may want to modify its internal implementation in the future to return a String []. If you want to maintain a certain degree of flexibility so that you can change the items returned by the method in the future, select a weak return type. Bytes ----------------------------------------------------------------------------------------------------AttributeAttribute allows the source code to use a simplified syntax to call a method. CLR supports two types of attributes: parameterless property. Parameterful property (indexer ).No parameter PropertyMany types define the status information that can be obtained or changed. This status information is generally implemented as a type of field member. C #'s anonymous type function can use very concise syntax to declare an immutable tuples. Tuples are types that contain a set of attributes. These attributes are usually associated in some form. An anonymous instance cannot be exposed to the outside of a method. In the method prototype, it cannot be required to accept an anonymous type parameter, because there is no way to execute the anonymous type. It cannot be specified to return a reference to an anonymous type. In addition to the anonymous and Tuple types, pay attention to the System. Dynamic. ExpandoObject class (defined in the System. Core. dll program ). This class can be used with the dynamic type of C # to combine a series of attributes (key-value pairs) in another way, the result of this operation is typed securely from time to time during compilation, but the syntax looks good.Parameter attributesThe parameter-free attribute is easy to understand because the get accessor method does not receive parameters and is similar to field access. In addition, the compiler supports the so-called parameterful property. Its get accesser method accepts one or more parameters, and the set accesser accepts two or more parameters. Different encoding languages make public parameter attributes in different forms, and their names are also different. C # language calls them indexers. Visual Basic is called the default attribute. C # expose the attributes of parameters (Indexer) in an array-style language ). In other words, indexes can be seen as a way for C # developers to reload the "[]" operator. CLR does not distinguish between the parameter-free attributes and the parameter attributes. For CLR, each attribute is only a pair of methods and metadata defined in the type. As mentioned above, different programming languages require different syntaxes to create and use parameters. Using this [...] As the syntax to express an indexer is purely a choice of the C # team. Therefore, C # Only Allows defining the indexer on the instance of the object, but does not provide syntax for defining the attributes of the static indexer, although CLR supports static parameters.Performance when calling the property accessors MethodFor simple get and set accessors, the JIT compiler will inline the code (inline ). In this way, the use of attributes (rather than fields) will have no performance loss. Inline is to compile the code of a method (or the accessor method in the current situation) directly into the method that calls it. This avoids the overhead of calling during runtime, and the cost is that the code of the compiled method will become larger. Note that the JIT compiler does not inline attribute methods when debugging code, because the Inline code becomes difficult to debug.

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.