【发布时间】:2013-10-28 21:28:51
【问题描述】:
我需要创建一个删除实例的类方法。
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? -
/*此方法将删除实例,因此对该实例的任何引用现在都将为空*/ 因此有关空分配的任何答案都是不正确的。
-
为什么需要这样做?当没有更多对它们的引用时,.NET 中的垃圾收集器将从内存中删除您的对象。您实际上要完成垃圾收集器不为您做的事情?听起来您面临的实际问题在设计中的其他地方。打个比方,您是在询问如何执行第 5 步,但您在第 2 步走错了方向。
-
如果你需要强制垃圾收集器那么你可以 GC.Collet()
-
亲爱的 StackOverflow:与其想出更多创造性的方法来删除实例,不如尝试帮助 OP 解决他的实际问题?在Old Shoe and a Glass Bottle 之间做出决定时,他不需要帮助。
标签: c# memory-management