C#对象初始化器的嵌套使用 [英] Nested use of C# Object Initializers

查看:112
本文介绍了C#对象初始化器的嵌套使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,对象初始值设定项非常方便-尤其是如果您正在使用linq时,它们是非常必要的-但我不太清楚这一点:

so, object initializers are all kinds of handy - especially if you're doing linq, where they're downright necessary - but I can't quite figure out this one:

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应该是未分配的局部变量。当您执行类似操作

this doesn't work, class1 is supposedly an unassigned local variable. it gets even trickier in Linq when you are doing something like

select new Class1() { ...

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

it doesn't even have a name to refer to it by!

我该如何解决?

推荐答案


我可以简单地不使用对象初始化程序进行嵌套引用吗?使用对象初始化程序?

can I simply not make nested references using object initializers?

您是对的,您不能。会有一个周期; A需要B进行初始化,但B之前需要A。确切地说,您当然可以创建嵌套的对象初始值设定项,但不能使用循环依赖项。

You are right - you cannot. There would be a cycle; A requires B for initialization but B requires A before. To be precise - you can of course make nested object initializers but not with circular dependencies.

但是您可以-我建议您应该尽可能解决-

But you can - and I would suggest you should if possible - work this around as follows.

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;
}

在属性内部建立关系的好处是,您无法获得不一致的状态如果您忘记初始化语句之一。显然,这是次优的解决方案,因为您需要两个语句才能完成一件事情。

Building the relation inside the property has the benifit that you cannot get an inconsitent state if you forget one of the initialization statements. It is quite obvious that this is an suboptimal solution because you need two statements to get one thing done.

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

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

With the logic in the properties you get the thing done with only one statement.

a.Child = b;

反之亦然。

b.Parent = a;

最后使用对象初始值设定项语法。

And finally with object initializer syntax.

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

这篇关于C#对象初始化器的嵌套使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆