How to delete object?

前端 未结 9 1331
眼角桃花
眼角桃花 2021-02-13 18:39

I need to create a method of class that delete the instance.

public class Car
{
    private string m_Color;

    public string Color
    {
        get { return m         


        
相关标签:
9条回答
  • 2021-02-13 19:03

    You can use extension methods to achive this.

    public static ObjRemoverExtension {
        public static void DeleteObj<T>(this T obj) where T: new()
        {
            obj = null;
        }
    }
    

    And then you just import it in a desired source file and use on any object. GC will collect it. Like this:Car.DeleteObj()

    EDIT Sorry didn't notice the method of class/all references part, but i'll leave it anyway.

    0 讨论(0)
  • 2021-02-13 19:04

    You cannot delete an managed object in C# . That's why is called MANAGED language. So you don't have to troble yourself with delete (just like in c++).

    It is true that you can set it's instance to null. But that is not going to help you that much because you have no control of your GC (Garbage collector) to delete some objects apart from Collect. And this is not what you want because this will delete all your collection from a generation.

    So how is it done then ? So : GC searches periodically objects that are not used anymore and it deletes the object with an internal mechanism that should not concern you.

    When you set an instance to null you just notify that your object has no referene anymore ant that could help CG to collect it faster !!!
    
    0 讨论(0)
  • 2021-02-13 19:05

    It sounds like you need to create a wrapper around an instance you can invalidate:

    public class Ref<T> where T : class
    {
        private T instance;
        public Ref(T instance)
        {
            this.instance = instance;
        }
    
        public static implicit operator Ref<T>(T inner)
        {
            return new Ref<T>(inner);
        }
    
        public void Delete()
        {
            this.instance = null;
        }
    
        public T Instance
        {
            get { return this.instance; }
        }
    }
    

    and you can use it like:

    Ref<Car> carRef = new Car();
    carRef.Delete();
    var car = carRef.Instance;     //car is null
    

    Be aware however that if any code saves the inner value in a variable, this will not be invalidated by calling Delete.

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