我正在调用一种删除包含特定值的对象的方法。它看起来像这样:
static public void RemovePiece(string BoardId)
{
LumberPiece board = LocateBoard(BoardId);
board = null;
}
LumberPiece是一个看起来像这样的类:
private class LumberPiece
{
public string boardID;
...
}
和LocateBoard是一个返回正确识别的LumberPiece对象的函数:
static private LumberPiece LocateBoard(string BoardId)
{
if (SawyerArea.lumber.boardID == BoardId)
return SawyerArea.lumber;
else if (SpliceArea1.lumber.boardID == BoardId)
return SpliceArea1.lumber;
else if (SpliceArea2.lumber.boardID == BoardId)
return SpliceArea2.lumber;
else
throw new Exception("Your LumberID was not found in any activity area. Has it already been removed? or are you handling the integer-String Conversion Correctly");
}
Area变量是此类的实例:
private class ActivityArea
{
public Sensor sensor;
public ClampSet clampSet;
public Servo servo;
public LumberPiece lumber;
public bool IsCurrentlyFilled()
{
if (lumber != null)
return true;
else
return false;
}
public ActivityArea(Sensor s, ClampSet cs, Servo srv)
{
sensor = s;
clampSet = cs;
servo = srv;
}
如何删除正确识别的LumberPiece对象?
答案 0 :(得分:8)
在像.NET这样的垃圾收集框架中,您不会“删除”该对象。你只是停止关心它。一旦你没有引用它(通过任何路由),垃圾收集器将在适当的时候处理它。
这可能涉及从列表中删除引用等 - 这通常很简单:
list.Remove(theObject);
但是,由于我们无法看到您存储电路板的位置,我们无法告诉您如何删除对它的引用。
实际上,您需要在此处完成的工作与非GC平台没有什么不同;您 仍然 需要从这些列表中删除指针,以避免在以后删除现在删除的指针时发生可怕的错误。
答案 1 :(得分:3)
您需要找到包含要删除的Lumber对象的ActivityArea
。
因此,对于示例,您可以使用此方法而不是LocateBoard:
static public ActivityArea LocateAreaByBoard(string BoardId)
{
if (SawyerArea.lumber.boardID == BoardId)
return SawyerArea;
else if (SpliceArea1.lumber.boardID == BoardId)
return SpliceArea1;
else if (SpliceArea2.lumber.boardID == BoardId)
return SpliceArea2;
else
throw new Exception("Your LumberID was not found in any activity area. Has it already been removed? or are you handling the integer-String Conversion Correctly");
}
然后您可以将删除代码更改为:
ActivityArea area = LocateAreaByBoard(BoardId);
area.lumber = null;
它会为您提供所需的删除效果