How to delete object?

前端 未结 9 1329
眼角桃花
眼角桃花 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 18:52

    From any class you can't set its value to null. This is not allowed and doesn't make sense also -

    public void Delete()
    {
        this = null; <-- NOT ALLOWED
    }
    

    You need an instance of class to call Delete() method so why not set that instance to null itself once you are done with it.

    Car car = new Car();
    // Use car objects and once done set back to null
    car = null;
    

    Anyhow what you are trying to achieve is not possible in C#. I suspect from your question that you want this because there are memory leaks present in your current design which doesn't let the Car instance to go away. I would suggest you better profile your application and identify the areas which is stopping GC to collect car instance and work on improving that area.

提交回复
热议问题