我需要創建一個刪除實例的類的方法。如何刪除對象?
public class Car
{
private string m_Color;
public string Color
{
get { return m_Color; }
set { m_Color = value; }
}
public Car()
{
}
public void Delete()
{
/*This method will delete the instance,
so any references to this instance will be now null*/
}
}
class Program
{
static void Main(string[] args)
{
Car car = new Car();
car.Delete();
if(car==null)
Console.WriteLine("It works.");
else
Console.WriteLine("It doesn't work.")
}
}
我想知道是否有任何可能的解決方案(即使它不被推薦)如何做到這一點。
此類的實例將存儲在數百個不同的類中。我會盡量說明這一點,例如會出現這些類:
public class CarKey
{
private Car m_Car;
public Car Car
{
get { return m_Car; }
}
public bool CarExist{ get{ return m_Car != null; } }
public CarKey(Car car)
{
m_Car = car;
}
}
public class Garages
{
private List<Car> m_Collection = new List<Car>();
private int m_Size;
public int Size{ get{ return m_Size; } }
public Garages(int size)
{
for(int i=0;i<size;i++)
m_Collection.Add(null);
}
public bool IsEmpty(int garage)
{
return m_Collection[garage] == null;
}
public void InsertCar(Car car, int garage)
{
if(m_Collection[garage] != null)
throw new Exception("This garage is full.");
m_Collection[garage] = car;
}
public Car GetCar(int garage)
{
if(m_Collection[garage] == null)
throw new Exception("There is no car, maybe it was deleted.");
return m_Collection[garage];
}
}
而不是'car.Delete()'爲什麼不簡單'car = null'? –
/*此方法將刪除實例,因此對此實例的任何引用現在都將爲空* /因此有關空值的任何答案均不正確。 – FLCL
我不能這樣做。在我的程序中將有數百個參考文獻在不同的地方和不同的格式,我無法管理它們。 – user1576055