CLR via C # Deep solution note Four-methods, parameters, properties

Source: Internet
Author: User

instance constructors and classes (reference types)A constructor (constructor) is a special method that allows an instance of a type to be initialized to a good state. The constructor method is always called. ctor in the method definition metadata table. When you create an instance of a reference type: #1, first allocate memory # # for the instance's data field, then initialize the object's additional fields (type object pointer and synchronization block index) #3, and finally call the type's instance constructor to set the object's initial state to construct the object of the reference type, before invoking the type's instance constructor. The memory allocated for an object is always zeroed first. The constructor does not show that all fields that are overridden are guaranteed to have a value of 0 or null. Unlike other methods, instance constructors can never be inherited.if the base class does not provide a parameterless constructor, the derived class must explicitly call a base class constructor, or the compiler will give an error. If the class's modifiers are static (sealed and abstract-static classes are abstract sealed classes in metadata), the compiler does not generate a default constructor in the class's definition at all. Note: Before invoking the constructor of the base class, the compiler initializes any fields that use the simplified syntax to maintain the impression that the source code left "These fields always a value." Instance constructors and structs (value types)The value type (struct) constructor works very differently from the constructor of the reference type (Class). The CLR is always allowed to create instances of value types, and there is no way to prevent instantiation of value types. The type defines the parameterless constructor, but the CLR is allowed. To enhance the run-time performance of your application, the C # compiler does not automatically generate such code (automatically calls the parameterless constructor of a value type, even if the value type provides a parameterless constructor). Therefore, value types do not actually need to define constructors. The C # compiler also does not generate a default parameterless constructor for value types at all. The CLR does allow the constructor to be defined for a value type and must be explicitly called, even if it is a parameterless constructor (this is to enhance application performance). In fact, the C # compiler is also not allowed to value Type ConstructorThe CLR also supports the type constructor, also known as the Static constructor (constructor), the class constructor (class constructor), or the type initializer (types initializer). Type constructors can be applied to interfaces (not allowed by the C # compiler), reference types, and value types. #1, the role of the instance constructor is to set the initial state of an instance of the type. Correspondingly, the role of the type constructor is to set the initial state of the type. Type constructors are not defined by default. If you define it, you can define only one and never have parameters. #2, the type constructor does not allow access modifiers, in fact it is always private and the C # compiler is automatically marked as private. It is private to prevent any code written by the developer from calling it, and calls to it are always the responsibility of the CLR. #3, the invocation of a type constructor is cumbersome. When the JIT compiler compiles a method, it looks at the types that are referenced in the code. Any type defines a type constructor, and the JIT compiler checks whether the type constructor has been executed against the current AppDomain. If the constructor is never executed, the JIT compiler adds a call to the type constructor in the local (native) code it generates. If the type constructor is already executed, the JIT compiler does not add a call to it because he knows that the type has been initialized. #4, when the method is compiled by the JIT compiler, the thread starts executing it and eventually executes the code that invokes the type constructor. Multiple threads may execute the same method at the same time. The CLR wants to make sure that in each AppDomain, a type constructor can only be executed once. To ensure this, the calling thread acquires a mutex thread synchronization lock when the type constructor is called. This way, if multiple thread views call a static type constructor of a type at the same time, only one thread can get the lock, and the other threads will be blocked (blocked). The first thread executes the code in the static constructor. When the first thread leaves the constructor, the waiting thread wakes up and discovers that the constructor's code has been executed. #5, although you can define a type constructor in a value type, never do it, because the CLR sometimes does not invoke a static type constructor for a value type. #6, the CLR guarantees that a type constructor executes only once in each AppDomain, and (this execution) is thread-safe, so it is well suited to initialize any single-instance (singleton) objects required by the type in the type constructor.   Finally, if the type constructor throws an unhandled exception, the CLR will assume that the type is not available. Attempting to access any field or method of that type will result in the throwing of a system.typeinitialIzationexception exception. Code in a type constructor can only access static fields of a type, and its general purpose is to initialize those fields. As with instance fields, C # provides a simple syntax to initialize static fields of a type.   operator overloading MethodsSome programming languages are instances that allow a type to define how an operator should manipulate the type. For example, many types (System.String) are overloaded with equal (= =) and unequal (! =) operator. The CLR knows nothing about operator overloading, and they don't even know what the operator is. It is the programming language that 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 of operators and programming languages: If a type defines an operator overloading method, Microsoft also recommends that the type define a more friendly public static method and invoke the operator overload method inside the method. The System.Decimal type of the FCL is a good example of how to overload operators and define friendly method names according to Microsoft's known principles. conversion Operator MethodSometimes you need to convert an object from one type to a different type. For example, sometimes you have to convert a byte type to a Int32 type. In fact, when both the source type and the target type are the primitive types of the compiler, the compiler knows for itself how to generate the code needed to convert the object. Some programming languages, such as C #, have overloads that provide conversion operators. A conversion operator is a method that converts an object from one type to another. You can use special syntax to define a method for converting operators. The CLR specification requires that the transform operator overload methods be public and static methods. In addition, C # requires both the parameter type and the return type to be the same as the type that defines the conversion method. The same in C #, the implicit keyword tells the compiler to invoke the method in order to generate code, and does not need to be explicitly transformed in the source code. Instead, the explicit keyword tells the compiler to call a method only if an explicit transformation is found. After the implicit or explicit keyword, to specify the operator keyword tells the compiler that the method is a conversion operator. After operator, specify what type the object needs to be converted to. Within the parentheses, specify what type to convert from. extension Methods  To apply an extension method: C # only supports extension methods, extension methods that do not support extended properties, extended events, extended operations (the method preceded by this first parameter) must be declared in a non-generic static class, but the class name has no limitations and can be any name. Of course, the extension method must have at least one parameter, and only the first parameter can be marked with the This keyword. When the C # compiler looks for extension methods defined in a static class, it requires that the static classes themselves have a file scope. When extending a method extension type, the derived type is also extended. Therefore, System.Object should not be used as the first parameter of an extension method, otherwise this method can be invoked on all expression types, causing the Visual Studio IntelliSense window to be populated with too much spam. The extension method has potential versioning problems. Extension methods, and you can also define extension methods for the interface type. The extension method is the basis of Microsoft's LINQ (Language Integrated Query, language-integrated queries) technology. The C # compiler allows you to create a delegate that references an extension method on an object. Action a = "Jeff". Showitems;a (); Partial MethodsThe return type of a partial method can only be declared in a partial class or struct that is always void, and no parameters can be marked with an out modifier. Because the method may not exist at run time, a variable is initialized to something that the method might return. You can have a ref parameter, which can be a generic method, either an instance or a static method. If there is no corresponding implementation part, you cannot create a delegate in your code to reference this partial method. Partial methods are always treated as private methods. ---------------------------------------------------------------------------------------------------- Parameters optional parameters and named parametersWhen designing parameters for a method, you can assign default values for some or all of the parameters. passing parameters to a method in a quoted mannerBy default, the CLR assumes that all method parameters are value-passed. When you pass an object of a reference type, a reference to an object (or to a pointer to an object) is passed to the method. Note that the reference (or pointer) itself is passed to the method in the form of a value. This means that the method can modify the object, and the caller can see the changes. When an instance of a value type is passed, a copy of the instance is passed to the method, which means that the method obtains a copy of the instance of the value type it is dedicated to, and the instance of the caller is not affected. keyword out or refIn C #, parameters are allowed to be passed as a reference rather than as a pass value. This is done with the keyword out or ref, telling the C # compiler to generate metadata to indicate that the parameter is referenced. The compiler will also generate code to pass the address of the parameter, rather than passing the parameter itself. The caller must allocate memory for the instance, and the callee will manipulate the memory (the content in). In the CLR perspective, the keyword out and ref are exactly the same. This means that the same IL code will be generated regardless of the keyword used. The metadata is almost identical, except for one bit, which is used to record whether the declaration method specifies out or ref. The C # compiler treats these two keywords differently, and the difference determines which method is responsible for initializing the referenced object. If the parameter of the method is marked with out, it indicates that the caller is not expected to initialize the good object before calling the method, and that the value must be written to before returning. In the case of a ref tag, the caller must initialize the value of the parameter before calling the method, and the called method can read the value and/or write to the value. In summary, from the IL and CLR perspectives, out and ref are the same matter: all result in a pointer passing to the instance. But from the compiler's point of view, the difference between the two, the compiler will follow the different standards (requirements) to verify that you write the correct code. Important notes:If the two overloaded methods are only the difference between out and ref, then it is not legal, because the metadata representation of two signatures is exactly the same. For a variable (argument) that is passed to a method by reference, its type must be the same as the type (formal parameter) declared in the method signature. known principles for parameters and return types  #1, when declaring a method's parameter type, you should specify the weakest type as much as possible, preferably an interface rather than a base class. For example, if you are writing a method to handle a set of data items, it is best to use an interface (such as ienumerable<t> to declare the parameters of the method) instead of a strong data type (such as list<t>) or a stronger interface type (such as icollection<   T> or ilist<t>).//Good public void additems<t> (Ienumerable<t> collection) {...}   Not good public void additems<t> (List<t> collection) {...} If you need to be a list (not just an enumerable object), you should declare the parameter type as ilist<t>. However, you will still want to avoid declaring parameter types as list<t>. Here's an example of a collection that is designed with an interface architecture. The concept also applies if you want to discuss classes that are designed using the base class architecture. such as://Good public void processbytes (Stream somestream) {...}//Bad public void Processbytes (FileStream FileStream) {...} first Methods can handle any kind of flow, including FileStream, NetworkStream, and MemoryStream.The second method only handles the FileStream stream, which limits its application. #2, the return type of the method is generally declared to be the strongest type (to avoid being limited to a particular type). For example, it is a good idea to declare a method to return a FileStream object instead of returning a stream object. Good public FileStream OpenFile () {...}//Bad public Stream OpenFile () {...} If a method returns a List<string> object, you may want to Modify its internal implementation to return a string[]. Select a weaker return type if you want to maintain some flexibility in order to change what the method returns in the future. ---------------------------------------------------------------------------------------------------- Propertiesproperty allows the source code to invoke a method with a simplified syntax. The CLR supports two properties: the parameterless attribute (parameterless property), which is referred to as the attribute. The parameter attribute (Parameterful property), the indexer (indexer). No Parameter PropertyMany types define state information that can be obtained or changed. This state information is generally implemented as a field member of a type.    argues that it should never be done like this. One of the important principles of object-oriented design and programming is Data Encapsulation (encapsulation). It means that a field of type should never be exposed, because it is easy to write code that improperly uses the field, thus destroying the state of the object. E.age =-5; Code corruption There are other reasons why we encapsulate access to data fields in types: First, you might want to access fields to perform some side effect, cache some values, or postpone the creation of some internal objects. Second, you might want to access the fields in a thread-safe manner. Third, the field may be a logical field whose value is not represented by the bytes in memory, but rather by an algorithm to calculate the gain. For these reasons, it is strongly recommended that all fields be set to private. To allow a user or type to get or set state information, expose a method for that purpose. Methods that encapsulate field access are often referred to as accessor (accessor) methods. Accessor methods can optionally check the reasonableness of the data to ensure that the state of the object is never destroyed.    this has two drawbacks. First, because you have to implement additional methods, you have to write more code, and second, the type of user must call the method, not directly drinking a field name. The   programming language and the CLR provide a mechanism called properties. It mitigates the impact of the first disadvantage, and completely eliminates the second one.    can think of attributes as smart fields (smart field), which is a field with extra logic behind it. The CLR supports static, instance, abstract, and virtual properties. In addition, properties can be marked with any accessibility modifier and may be defined in the interface. A property has a name and a type (the type cannot be void). It is common to use the property's get and set methods to manipulate private fields defined within a type. Private fields are often called support fields (backing field). However, the get and set methods do not necessarily access the support fields. C # has built-in support for attributes, and when the C # compiler discovers that code view Gets or sets a property, it actually generates a call to one of these methods. In addition to generating corresponding accessor methods for each property defined in the source code, the compiler also generates a property definition item in the metadata of the managed assembly. In this record entry, there are flags (flags) and the type of the property. In addition, it references the get and set accessor methods. The only function of this information is to create a "property" between the abstract concept and its accessor methods.Contact. The CLR does not use these metadata information and requires only accessor methods at run time.   reasonably define attributesProperties look similar to fields, but are essentially methods. This has caused a lot of misunderstanding. object and collection initializersIt is often necessary to construct an object and then set some public properties (or fields) of the object. The following initialization method simplifies the object initialization programming pattern: Anonymous Typethe anonymous type feature of C # allows you to declare an immutable tuple type using very concise syntax. A tuple type is a type that contains a set of attributes, which are usually associated with one another in some form. Create an anonymous type, do not execute the type name after the new keyword, the compiler automatically creates a type name for it, and does not tell me what the name is specifically (this is where the word anonymous comes from). You can take advantage of the implicit type local variables function (VAR) of C #. Compiler definition Anonymous type very "understanding", if it sees you have defined multiple anonymous types in the source code, and those types have the same structure, it will only create an anonymous type definition, but create multiple instances of that type. The so-called "same structure" means that in these anonymous types, each property has the same type and name, and the specified order of the properties is the same. Exactly the identity of the type, you can create an implicitly typed array that contains an object of the set of anonymous types. Anonymous types are often used in conjunction with LINQ (Language intergrated Query, language-integrated queries) technology. You can execute a query by using LINQ, which generates a collection of objects that are the same anonymous type. The objects in the result set can then be processed. All of this happens in the same way.An instance of an anonymous type cannot be leaked to the outside of a method. In a method prototype, it cannot be required to accept an anonymous type parameter because there is no way to perform an anonymous type. It is also not possible to specify that it returns a reference to an anonymous type. In addition to the anonymous and tuple types, note the System.Dynamic.ExpandoObject class (defined in the System.Core.dll assembly). This class, in conjunction with the dynamic type of C #, allows you to combine a series of attributes (key-value pairs) in a different way, with the result that the compile-time type is safe, but the syntax looks good. have parameter PropertiesNo parameter property because the get accessor method does not receive parameters and is somewhat similar to field access, these properties are easy to understand. In addition, the compiler supports the so-called parameter attribute (parameterful property), whose get accessor method accepts one or more parameters, and the set accessor accepts two or more parameters. Different coding languages expose the parameter attributes in different forms, and the salutation is different. The C # language calls them indexers. Visual Basic is called the default property. C # uses an array-style language to expose a parameter attribute (indexer).  In other words, an index can be seen as a way for C # developers to overload the "[]" operator. The CLR itself does not differentiate between the parameterless attribute and the parameter attribute. For the CLR, each property is just a pair of methods and some metadata defined in the type. As mentioned earlier, different programming languages require different syntax to create and use a parameter attribute. It is purely the C # team's own choice to use this[as the syntax for expressing an indexer. Therefore, C # simply allows the indexer to be defined on an instance of an object without providing the syntax to define static indexer properties, although the CLR supports static, parameter-aware properties. performance when invoking a property accessor methodFor simple get and set accessor methods, the JIT compiler will code inline (inline). This way, there is no performance penalty for using attributes instead of using fields. Inline is the code that compiles a method (or accessor method in the current case) directly into the method that calls it. This avoids the overhead of making calls at run time, at the expense of the code of the compiled method becomes larger. Note that the JIT compiler does not inline property methods when debugging code, because the inline code becomes difficult to debug.

CLR via C # Deep solution note Four-methods, parameters, properties

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.