【发布时间】:2021-05-02 12:00:27
【问题描述】:
我正在尝试更新递归代码中的 self 对象列表,但它没有这样做,但是通过更改值来更新对象时工作正常!
namespace Test
{
class Program
{
static void Main(string[] args)
{
Node main = new Node();
main.Sequence = "1";
main.Id = 1;
main.ChildNodes.Add(new Node()
{
Sequence = "1.1",
Id = 2
});
main.ChildNodes.Add(new Node()
{
Sequence = "1.2",
Id = 3
});
main.ChildNodes.Add(new Node()
{
Sequence = "1.3",
Id = 4
});
Console.WriteLine("Before :");
PrintNode(main);
Console.WriteLine();
MakeNull(main);
Console.WriteLine("After :");
PrintNode(main);
void MakeNull(Node node)
{
foreach (var Child in node.ChildNodes)
{
MakeNull(Child);
}
node.ChildNodes.RemoveAll(p => p == null);
if (node.ChildNodes.Count == 0)
{
node.Id = 5;//this is working
node = null;//this is not, why ?
}
}
Console.ReadLine();
}
static void PrintNode(Node node)
{
Console.WriteLine("Id:" + node.Id + " Sequence:" + node.Sequence);
for (int i = 0; i < node.ChildNodes.Count; i++)
{
PrintNode(node.ChildNodes[i]);
}
}
}
public class Node
{
public int Id { get; set; }
public string Sequence { get; set; }
public List<Node> ChildNodes { get; set; }
public Node()
{
ChildNodes = new List<Node>();
}
}
}
为什么不让整个对象为空?
【问题讨论】:
-
如果您随后将该对象设置为空,那么设置对象属性的意义何在??
-
你想创建一个
IDisposable-like 对象吗? -
将变量设置为 null 只会影响该局部变量(在这种情况下是一个参数)。它对该功能的外部完全没有任何作用。也许您想查看
ref参数? -
@Liam 设置属性仅用于演示目的,实际上我需要将其设为 null 但不能
-
@Alejandro 虽然我正在更新它的属性,但它工作正常,但是当它变为 null 时它不会工作,为什么会这样?