gpt4 book ai didi

c# - 如何通过构造函数正确初始化两个类之间的父子引用

转载 作者:太空狗 更新时间:2023-10-29 21:34:02 36 4
gpt4 key购买 nike

我有两个类(class)。第一类是Parent,它有一个对象列表(Child)。每个 Child 都有对他的 Parent 类的引用。问题是如何通过构造函数实现这个引用。

public sealed class Child
{
public Child(string id, string name, Parent parent)
{
Id = id;
Name = name;
Parent = parent;
}

public Parent ParentInstance { get; private set; }
public string Id { get; private set; }
public string Name { get; private set; }
}

public sealed class Parent
{
public Parent(string id, string name, IEnumerable<Child> children)
{
Id = id;
Name = name;
Children = children;
}

public string Id { get; private set; }
public string Name { get; private set; }
public IEnumerable<Child> Children { get; private set; }
}

问题是我有一个代码可以解析一些 XML 代码并创建 Parent 对象列表。这是示例:

internal Parent ParseParent(XElement parentXElement)
{
return new Parent(parentXElement.Attribute("id").Value, parentXElement.Attribute("name").Value, parentXElement.Descendants("child").Select(ParseChild));
}

当然我可以在 Parent 构造函数中初始化 Parent 属性,只需从 Parent setter 中删除 private然后遍历所有 child 并使用此属性。但我想让它只读。像这样:

public Parent(string id, string name, IEnumerable<Child> children)
{
Id = id;
Name = name;
Children = children.ForEach(c => c.ParentInstance = this);
}

最佳答案

要不可变包含循环引用,您需要这样的东西:

public sealed class Parent
{
private readonly IEnumerable<Child> children;
private readonly string name; // Just for example

public Parent(XElement element)
{
name = (string) element.Attribute("name");
children = element.Elements("Child")
.Select(x => new Child(x, this))
.ToImmutableList(); // Or whatever collection you want
}
}

public sealed class Child
{
private readonly Parent parent;
private readonly string name; // Just for example

public Child(XElement element, Parent parent)
{
this.name = (string) element.Attribute("name");
// Better not ask the parent for its children yet - they won't be
// initialized!
this.parent = parent;
}
}

Child 构造函数中的注释应该让您大吃一惊。尽管 Parent 是不可变的,但我们在完成初始化之前就泄漏了 this ...所以 Child 构造函数需要确保它不会在构造过程中尝试找到它的 sibling 。

关于c# - 如何通过构造函数正确初始化两个类之间的父子引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21236148/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com