删除C#中返回的对象的属性

jth*_*h41 1 c#

我正在调用一种删除包含特定值的对象的方法.它看起来像这样:

static public void RemovePiece(string BoardId)
{
    LumberPiece board = LocateBoard(BoardId);
    board = null;
}
Run Code Online (Sandbox Code Playgroud)

LumberPiece是一个看起来像这样的类:

private class LumberPiece
{
    public string boardID;
    ...
}
Run Code Online (Sandbox Code Playgroud)

和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");
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
Run Code Online (Sandbox Code Playgroud)

如何删除正确识别的LumberPiece对象?

Mar*_*ell 8

在像.NET这样的垃圾收集框架中,您不会"删除"该对象.你只是停止关心它.一旦你没有引用它(通过任何路由),垃圾收集器将在适当的时候处理它.

这可能涉及从列表中删除引用等 - 这通常很简单:

list.Remove(theObject);
Run Code Online (Sandbox Code Playgroud)

但是,由于我们无法看到您存储板的位置,因此我们无法告诉您如何删除对它的引用.

实际上,您需要在此处完成的工作与非GC平台没有什么不同; 你仍然需要从这些列表中删除指针,以避免在以后删除现在删除的指针时出现可怕的错误.