我需要创建一个删除实例的类的方法。如何删除对象?
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