What is the .NET object life cycle?

前端 未结 9 2071
一个人的身影
一个人的身影 2020-12-29 09:05

What is the object life cycle for an object in .NET?

From what I understand it is:

  1. Object created - constructor called (if one exists)
  2. Methods
相关标签:
9条回答
  • 2020-12-29 09:30

    A point about the constructor:

    Every class has one, as one will be generated by the compiler if you don't code it yourself. And the first thing this does (unless specified otherwise), is to call the ctor of it's parent type.

    0 讨论(0)
  • 2020-12-29 09:32

    Here is a detailed descriptin of the question. First, Dispose is not called by runtime, you have to call it yourself. There are also no destructors, but finalizers: if an object overrides a Finalized method, it is called when the object is no longer accessible for the application. It may happen that during finalization the object becomes accessible again (for example, stores a reference to itself in a global object), so it returns to step 2 of your model. There are also methods in GC object that let the user control object finalization.

    0 讨论(0)
  • 2020-12-29 09:32

    The Object Life Cycle

    Creating an object: You use the new keyword to instantiate the new object.

    1. A block of memory is allocated. This block of memory is big enough to hold the object. (CLR handles the allocation of memory for managed objects)
    2. The block of memory is converted to an object. The object is initialized. (You can control this step by implementing a constructor)

    Destroying an Object: You use destruction to reclaim any resources used by that object.

    1. The object is cleaned up; for example, by releasing any unmanaged resources used by the application, such as file handles and database connections. (You can control this step by implementing a destructor.)
    2. The memory used by the object is reclaimed.

    The CLR handles the release of memory used by managed objects; however, if you use unmanaged objects, you may need to manually release the memory used by these items.

    0 讨论(0)
提交回复
热议问题