How to delete object?

前端 未结 9 1355
眼角桃花
眼角桃花 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:05

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

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

    and you can use it like:

    Ref 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.

提交回复
热议问题