How to delete object?

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

    FLCL's idea is very correct, I show you in a code:

        public class O1 where T: class
        {
            public Guid Id { get; }
            public O1(Guid id)
            {
                Id = id;
            }
            public bool IsNull => !GlobalHolder.Holder.ContainsKey(Id);
            public T Val => GlobalHolder.Holder.ContainsKey(Id) ? (T)GlobalHolder.Holder[Id] : null;
        }
        public class GlobalHolder
        {
            public static readonly Dictionary Holder = new Dictionary();
            public static O1 Instantiate() where T: class, new()
            {
                var a = new T();
                var nguid = Guid.NewGuid();
                var b = new O1(nguid);
                Holder[nguid] = a;
                return b;
            }
            public static void Destroy(O1 obj) where T: class
            {
                Holder.Remove(obj.Id);
            }
        }
    
        public class Animal
        {
    
        }
    
        public class AnimalTest
        {
            public static void Test()
            {
                var tom = GlobalHolder.Instantiate();
                var duplicateTomReference = tom;
                GlobalHolder.Destroy(tom);
                Console.WriteLine($"{duplicateTomReference.IsNull}");
                // prints true
            }
        }
    

    Note: In this code sample, my naming convention comes from Unity.

提交回复
热议问题