简体   繁体   中英

Can I set something up to make a class do something on unload

If I have a class,

class order()
{
    int orderId {get;set;}
    double total {get;set;}
    public order(){}
    ...
}

Is there something I can overload so that c# does something every time it is going to be unloaded, instead of telling it I want it to be done?

   static void Main(string[] args)
        {
            Order activeOrder = new Order();
            // do stuff to the order
            activeOrder = new Order(); <---- Automatically commit any changes to the order, since I am starting a new one. 
        }

What you're asking doesn't really make sense. When you assign a new Order instance to the activeOrder variable, the first Order instance isn't "unloaded". It just becomes eligible to garbage collection (unless it is also referenced somewhere else). This means that the next time the GC will run, the instance will be collected, and the finalizer will run if it's defined. The problem is that it's completely non-deterministic: you don't know when the GC will run.

There is no way for the Order class to detect that the variable is assigned a new instance. All you can do is write a finalizer, but since you don't know when it will run, it's probably not a good idea. You should commit the changes explicitly when you're done working with the current Order .

Thread-safety aside:

class Order()
{
  static Order instance;

  int orderId {get;set;}
  double total {get;set;}
  public Order()
  {
    if (instance != null)
      instance.Unload();
    instance = this;
  }
  ...
  public Unload()
  {
  }
}

This still leaves a question of who will unload the last instance of Order .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM