1.Instance Constructors and Classes (Reference Types)

Constructors methods :

  1.allow an instance of a type to be initialized to a good state.

  2.are always called .ctor (for constructor) in a method definition metadata table.

  3.When creating an instance of a reference type, memory is allocated for the instance’s data fields, the object’s overhead fields (type object pointer and sync block index) are initialized, and then the type’s instance constructor is called to set the initial state of the object.

  3.When constructing a reference type object, the memory allocated for the object is always zeroed out before the type’s instance constructor is called. Any fields that the constructor doesn’t explicitly overwrite are guaranteed to have a value of 0 or null.

  4.instance constructors are never inherited. That is, a class has only the instance constructors that the class itself defines.

  Because instance constructors are never inherited, you cannot apply the following modifiers to an instance constructor: virtual, new, override, sealed, or abstract.

  5.If you define a class that does not explicitly define any constructors, the C# compiler defines a default (parameterless) constructor for you whose implementation simply calls the base class’s parameterless constructor.

  =

  If the class is abstract, the compiler-produced default constructor has protected accessibility;otherwise, the constructor is given public accessibility.

  If the base class doesn’t offer a parameterless constructor, the derived class must explicitly call a base class constructor or the compiler will issue an error.

  If the class is static (sealed and abstract), the compiler will not emit a default constructor at all into the class definition.

  6.define several instance constructors. Each constructor must have a different signature,and each can have different accessibility.

  7.For verifiable code, a class’s instance constructor must call its base class’s constructor before accessing any of the inherited fields of the base class.

  The C# compiler will generate a call to the default base class’s constructor automatically if the derived class’s constructor does not explicitly invoke one of the base class’s constructors.

  Ultimately, System.Object’s public,parameterless constructor gets called. This constructor does nothing—it simply returns. This is because System.Object defines no instance data fields, and therefore its constructor has nothing to do.

  8.In a few situations, an instance of a type can be created without an instance constructor being called.

    In particular, calling Object’s MemberwiseClone method allocates memory, initializes the object’s overhead fields, and then copies the source object’s bytes to the new object.

  Also, a constructor is usually not called when deserializing an object with the runtime serializer. The deserialization code allocates memory for the object without calling a constructor by using the System.Runtime.Serialization.FormatterServices type's GetUninitializedObject or GetSafeUninitializedObject methods.

  9.You should not call any virtual methods within a constructor that can affect the object being constructed.

  The reason is if the virtual method is overridden in the type being instantiated, the derived type’s implementation of the overridden method will execute,but all of the fields in the hierarchy have not been fully initialized.

  Calling a virtual method would therefore result in unpredictable behavior.

compiling:

  1.a simple syntax that allows the initialization of fields defined within a reference type when an instance of the type is constructed

  

  examine the Intermediate Language (IL) for SomeType’s constructor method (also called .ctor)

  

  SomeType’s constructor contains code to store a 5 into m_x and then calls the base class’s constructor.

  In other words, the C# compiler allows the convenient syntax that lets you initialize the instance fields inline and translates this to code in the constructor method to perform the initialization.

  2. you should be aware of code explosion.

  The compiler initializes any fields by using the convenient syntax before calling a base class’s constructor to maintain the impression that these fields always have a value as the source code appearance dictates. 

  

  When the compiler generates code for the three constructor methods.

    the beginning of each method includes the code to initialize m_x, m_s, and m_d.

  then, the compiler inserts a call to the base class’s constructor.

    then, the compiler appends to the method the code that appears in the constructor methods.

  For example, the code generated for the constructor that takes a String parameter includes the code to initialize m_x, m_s, and m_d, call the base class’s (Object’s) constructor, and then overwrite m_d with the value 10. Note that m_b is guaranteed to be initialized to 0 even though no code exists to explicitly initialize it.

  3.The potential problem occurs when a base class’s constructor invokes a virtual method that calls back into a method defined by the derived class.

  If this happens, the fields initialized by using the convenient syntax have been initialized before the virtual method is called.

  4.If you have several initialized instance fields and a lot of overloaded constructor methods, you should consider defining the fields without the initialization, creating a single constructor that performs the common initialization, and having each constructor explicitly call the common initialization constructor.

  This approach will reduce the size of the generated code.

  example:there are three constructors in the preceding class, the compiler generates the code to initialize m_x, m_s, and m_d three times—once per constructor.

  

2.Instance Constructors and Structures (Value Types)

Value type (struct) constructors:

  work quite differently from reference type (class) constructors.

  1.The common language runtime (CLR) always allows the creation of value type instances, and there is no way to prevent a value type from being instantiated.

  For this reason, value types don’t actually even need to have a constructor defined within them, and the C# compiler doesn't emit default parameterless constructors for value types.

  2.Strictly speaking, value type fields are guaranteed to be 0/null when the value type is a field nested within a reference type. However, stack-based value type fields are not guaranteed to be 0/null.

  For verifiability, any stack-based value type field must be written to prior to being read. If code could read a value type’s field prior to writing to the field, a security breach is possible.

  C# and other compilers that produce verifiable code ensure that all stack-based value types have their fields zeroed out or at least written to before being read so that a verification exception won’t be thrown at run time. 

  For the most part,this means that you can assume that your value types have their fields initialized to 0, and you can completely ignore everything in this note.

  3.although C# doesn’t allow value types with parameterless constructors, the CLR does.

  So if the unobvious behavior described earlier doesn’t bother you, you can use another programming language (such as IL assembly language) to define your value type with a parameterless constructor.

  Because C# doesn’t allow value types with parameterless constructors, compiling the following type produces the following message: error CS0573: 'SomeValType.m_x': cannot have instance field initializers in structs.

   

  4.any constructors that you do have for a value type must initialize all of the type’s fields.

  because verifiable code requires that every field of a value type be written to prior to any field being read

  

  When compiling this type, the C# compiler produces the following message: error CS0171:Field 'SomeValType.m_y' must be fully assigned before control leaves the constructor.

  To fix the problem, assign a value (usually 0) to y in the constructor. or do like this below

  

  this represents an instance of the value type itself and you can actually assign to it the result of newing up an instance of the value type, which really just zeroes out all the fields.

  In a reference type’s constructor, this is considered read-only, so you cannot assign to it at all.

compliling:

  1.To construct a Rectangle, the new operator must be used, and a constructor must be specified.

  

  In this case, the default constructor automatically generated by the C# compiler is called.

  When memory is allocated for the Rectangle, the memory includes the two instances of the Point value type. For performance reasons, the CLR doesn’t attempt to call a constructor for each value type field contained within the reference type. But as I mentioned earlier, the fields of the value types are initialized to 0/null.

  A value type’s instance constructor is executed only when explicitly called.

  2.The CLR does allow you to define constructors on value types. The only way that these constructors will execute is if you write code to explicitly call one of them.

  

  A value type’s instance constructor is executed only when explicitly called. So if Rectangle’s constructor didn’t initialize its m_topLeft and m_bottomRight fields by using the new operator to call Point’s constructor, the m_x and m_y fields in both Point fields would be 0.

  many compilers will never emit code to call a value type’s default constructor automatically, even if the value type offers a parameterless constructor.because to improve the run-time performance of the application,the C# compiler doesn’t automatically emit this code.

  To have a value type’s parameterless constructor execute, the developer must add explicit code to call a value type’s constructor.

  3.C# purposely disallows value types from defining parameterless constructors to remove any confusion a developer might have about when that constructor gets called.

  If the constructor can’t be defined, the compiler can never generate code to call it automatically.

  Without a parameterless constructor, a value type’s fields are always initialized to 0/null.

     

  C# doesn’t allow a value type to define a parameterless constructor. So the previous code won’t actually compile. The C# compiler produces the following message when attempting to compile that code: error CS0568: Structs cannot contain explicit parameterless constructors.

3.Type Constructors

type constructors:

  also known as static constructors,class constructors, or type initializers

  1.can be applied to interfaces (although C# doesn’t allow this), reference types, and value types.

  2.are used to set the initial state of a type. By default, types don’t have a type constructor defined within them.

  If a type has a type constructor, it can have no more than one.

  In addition, type constructors never have parameters

  

  type constructors just as you would parameterless instance constructors,except that you must mark them as static.

  3.type constructors should always be private,C# makes them private for you automatically.

  In fact, if you explicitly mark a type constructor as private (or anything else) in your source code, the C# compiler issues the following error: error CS0515: 'SomeValType.SomeValType()': access modifiers are not allowed on static

constructors.

  Type constructors should be private to prevent any developer-written code from calling them; the CLR is always capable of calling a type constructor.

  4.Although you can define a type constructor within a value type, you should never actually do this

  because there are times when the CLR will not call a value type’s static type constructor

  

  5.The calling of a type constructor is a tricky thing.

  When the just-in-time (JIT) compiler is compiling a method, it sees what types are referenced in the code.If any of the types define a type constructor,the JIT compiler checks if the type’s type constructor has already been executed for this AppDomain.

  If the constructor has never executed, the JIT compiler emits a call to the type constructor into the native code that the JIT compiler is emitting.

  If the type constructor for the type has already executed,the JIT compiler does not emit the call because it knows that the type is already initialized.

  6.it is possible that multiple threads will be executing the same method concurrently.The CLR wants to ensure that a type’s constructor executes only once per AppDomain.

  To guarantee this, when a type constructor is called, the calling thread acquires a mutually exclusive thread synchronization lock. So if multiple threads attempt to simultaneouslycall a type’s static constructor, only one thread will acquire the lock and the other threads will block.

  The first thread will execute the code in the static constructor. After the first thread leaves the constructor, the waiting threads will wake up and will see that the constructor’s code has already been executed. These threads will not execute the code again; they will simply return from the constructor method.

  In addition, if any of these methods ever get called again, the CLR knows that the type constructor has already executed and will ensure that the constructor is not called again.  

  7.Because the CLR guarantees that a type constructor executes only once per AppDomain and is thread-safe, a type constructor is a great place to initialize any singleton objects required by the type.

  8.Within a single thread, there is a potential problem that can occur if two type constructors contain code that reference each other

  For example, ClassA has a type constructor containing code that references ClassB, and ClassB has a type constructor containing code that references ClassA

  the CLR still guarantees that each type constructor’s code executes only once;

  however, it cannot guarantee that ClassA’s type constructor code has run to completion before executing ClassB’s type constructor.

  You should certainly try to avoid writing code that sets up this scenario.

  In fact, because the CLR is responsible for calling type constructors, you should always avoid writing any code that requires type constructors to be called in a specific order.

  9.if a type constructor throws an unhandled exception, the CLR considers the type to be unusable.

  Attempting to access any fields or methods of the type will cause a System.TypeInitializationException to be thrown.

  10.in a type constructor has access only to a type’s static fields, and its usual purpose is to initialize those fields.

  11.Although C# doesn’t allow a value type to use inline field initialization syntax for instance fields, it does allow you to use it for static fields.

  

  In other words, if you change the SomeType type above from a class to a struct, the code will compile and work as expected

compiling:

  1.the compiler automatically generates a type constructor

      ->           ->     

  Using ILDasm.exe, it’s easy to verify what the compiler actually produced by examining the IL for the type constructor. Type constructor methods are always called .cctor (for class constructor) in a method definition metadata table.

  2.Type constructors shouldn’t call a base type’s type constructor. Such a call isn’t necessary

  because none of a type’s static fields are shared or inherited from its base type.

  Some languages, such as Java, expect that accessing a type causes its type constructor and all of its base type’s type constructors to be called.

  In addition, interfaces implemented by the types must also have their type constructors called.

  The CLR doesn’t offer this behavior. However, the CLR does offer compilers and developers the ability to provide this behavior via the RunClassConstructor method offered by the System.Runtime.CompilerServices.RuntimeHelpers type.

  Any language that requires this behavior would have its compiler emit code into a type’s type constructor that calls this method for all base types.

  When using the RunClassConstructor method to call a type constructor, the CLR knows if the type constructor has executed previously and, if it has, the CLR won’t call it again.

  3.when the C# compiler generates IL code for the type constructor, it first emits the code required to initialize the static fields followed by the explicit code contained in your type constructor method.

  

  This constructor first initializes s_x to 5 and then initializes s_x to 10.

  4.if there’s a way to get some code to execute when a type is unloaded?

   yes,you can register a callback method with the System.AppDomain type’s DomainUnload event.

  many developers to believe that they could add a static Finalize method to the type, which will automatically get called when the type is unloaded?

  No.

  types are unloaded only when the AppDomain unloads. When the AppDomain unloads, the object that identifies the type becomes unreachable, and the garbage collector reclaims the type object’s memory. This behavior leads many developers to believe it.

  Unfortunately, the CLR doesn’t support static Finalize methods.All is not lost.

 

8.Methods(一)的更多相关文章

  1. How to implement equals() and hashCode() methods in Java[reproduced]

    Part I:equals() (javadoc) must define an equivalence relation (it must be reflexive, symmetric, and ...

  2. Sort Methods

    heyheyhey ~~ It has been a long time since i come here again...whatever today i will summerize some ...

  3. Top 10 Methods for Java Arrays

    作者:X Wang 出处:http://www.programcreek.com/2013/09/top-10-methods-for-java-arrays/ 转载文章,转载请注明作者和出处 The ...

  4. Don’t Use Accessor Methods in Initializer Methods and dealloc 【初始化和dealloc方法中不要调用属性的存取方法,而要直接调用 _实例变量】

    1.问题:    在dealloc方法中使用[self.xxx release]和[xxx release]的区别? 用Xcode的Analyze分析我的Project,会列出一堆如下的提示:Inco ...

  5. C# Extension Methods

    In C#, extension methods enable you to add methods to existing class without creating a new derived ...

  6. CLR via C# 3rd - 08 - Methods

       Kinds of methods        Constructors      Type constructors      Overload operators      Type con ...

  7. 转 Dynamics CRM Alert and Notification JavaScript Methods

    http://www.powerobjects.com/2015/09/23/dynamics-crm-alert-and-notification-javascript-methods/ Befor ...

  8. AX7: HOW TO USE CLASS EXTENSION METHODS

    AX7: HOW TO USE CLASS EXTENSION METHODS   To create new methods on a standard AX class without custo ...

  9. Keeping Async Methods Alive

    Consider a type that will print out a message when it’s finalized, and that has a Dispose method whi ...

  10. 增强学习(四) ----- 蒙特卡罗方法(Monte Carlo Methods)

    1. 蒙特卡罗方法的基本思想 蒙特卡罗方法又叫统计模拟方法,它使用随机数(或伪随机数)来解决计算的问题,是一类重要的数值计算方法.该方法的名字来源于世界著名的赌城蒙特卡罗,而蒙特卡罗方法正是以概率为基 ...

随机推荐

  1. OpenStack主机列表接口

    如之前讨论,openstack提供一套接口给运维管理平台,运维管理平台通过获取到的IP地址对主机进行监控. 接口名  请求地址  请求方法  请求cookie  请求头  返回值  返回值使用  登录 ...

  2. linux_c学习笔记之curl的使用一

    参考文档 使用libcurl发送PUT请求上传数据以及DELETE请求删除数据 http://blog.163.com/lixiangqiu_9202/blog/static/535750372014 ...

  3. android 项目学习随笔十五(ShareSDK开放平台)

    ShareSDK开放平台http://www.mob.com/#/

  4. ftp 终端命令

    近期使用 macbook,并与新买的路由器折腾, 先备着... http://blog.csdn.net/qinde025/article/details/7595102 ftp使用的内部命令如下(其 ...

  5. Datatables带参重绘

    研究了好久,最后发现只需要加上参数("bDestory":true,) 即可实现每次刷新就是新的重绘,而无需调用什么desctory init clear等等函数..

  6. Backup: Array in Perl6

    Array in Perl6 继承List,而List又继承Iterable,Positional,Cool ARRAY.pop ARRAY.shift ARRAY.push: VALUES ARRA ...

  7. ctl 里面pdef解说

    WRF 模式MM5 模式都是目前从网上可以下载的气象软件,因此在国内经常可以见到.但这两种模式的数据特点数据的水平网格都不是标准的经纬度网格.需要在ctl 文件中加入PDEF 定义说明把这种非标准的数 ...

  8. [转]Using the Group Pane to Repeat Page Titles

    转自:http://www.wiseowl.co.uk/blog/s148/group-pane-advanced-mode.htm Repeating Page Headers in Reporti ...

  9. 用excel2010 制作复合图表

    用excel2010制作双轴柱线复合图表就是要用excel2010做一个这样的图表:

  10. HDU 2236:无题II(二分搜索+二分匹配)

    http://acm.hdu.edu.cn/showproblem.php?pid=2236 题意:中文题意. 思路:先找出最大和最小值,然后二分差值,对于每一个差值从下界开始枚举判断能不能二分匹配. ...