gpt4 book ai didi

c# - C# 对象初始化器的嵌套使用

转载 作者:太空狗 更新时间:2023-10-29 18:26:15 26 4
gpt4 key购买 nike

所以,对象初始值设定项非常方便——尤其是当你在做 linq 时,它们是绝对必要的——但我不太明白这个:

public class Class1 {
public Class2 instance;
}

public class Class2 {
public Class1 parent;
}

这样使用:

Class1 class1 = new Class1();
class1.instance = new Class2();
class1.parent = class1;

作为初始化器:

Class1 class1 = new Class1() {
instance = new Class2() {
parent = class1
}
};

这不起作用,class1 应该是一个未分配的局部变量。当你做类似的事情时,它在 Linq 中变得更加棘手

select new Class1() { ...

它甚至没有一个名字来引用它!

我该如何解决这个问题?我可以不使用对象初始值设定项进行嵌套引用吗?

最佳答案

can I simply not make nested references using object initializers?

你是对的 - 你不能。会有一个循环; A 需要 B 进行初始化,但 B 之前需要 A。准确地说 - 您当然可以制作嵌套对象初始化器,但不能使用循环依赖。

但您可以 - 我建议您应该尽可能 - 按以下方式解决此问题。

public class A
{
public B Child
{
get { return this.child; }
set
{
if (this.child != value)
{
this.child = value;
this.child.Parent = this;
}
}
}
private B child = null;
}

public class B
{
public A Parent
{
get { return this.parent; }
set
{
if (this.parent != value)
{
this.parent = value;
this.parent.Child = this;
}
}
}
private A parent = null;
}

在属性内部建立关系的好处是,如果您忘记了其中一个初始化语句,就不会得到不一致的状态。很明显,这是一个次优解决方案,因为您需要两条语句才能完成一件事。

b.Parent = a;
a.Child = b;

使用属性中的逻辑,您只需一条语句即可完成任务。

a.Child = b;

或者反过来。

b.Parent = a;

最后是对象初始化语法。

A a = new A { Child = new B() };

关于c# - C# 对象初始化器的嵌套使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/795460/

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