使用Object Initializer声明嵌套对象时,从匿名子对象引用匿名父对象



如果我有一组父类、子类、孙类,其中孙类需要它的父类作为构造函数参数,是否有任何方法仍然可以使用嵌套的Object Initializers声明?

例如,考虑发票标题、发票行、发票行细分:

public class InvoiceHeaderModel
{
public List<InvoiceLineModel> InvoiceLineModels { get; set; }
}
public class InvoiceLineModel
{
public List<InvoiceLineBreakdown> InvoiceLineBreakdowns { get; set; }
}
public class InvoiceLineBreakdown
{
public InvoiceLineBreakdown(InvoiceLineModel parentInvoiceLine)
{
_parentInvoiceLine = parentInvoiceLine;
}
private InvoiceLineModel _parentInvoiceLine;
}

我想做的是:

public InvoiceHeaderModel BuildAnInvoice()
{
return new InvoiceHeaderModel
{
InvoiceLineModels = new List<InvoiceLineModel>
{
new InvoiceLineModel
{
InvoiceLineBreakdowns = new List<InvoiceLineBreakdown>
{
new InvoiceLineBreakdown(/* Need to reference the anonymous outer InvoiceLineModel*/),
new InvoiceLineBreakdown()
}
}
}
};
}

但是我不能,因为InvoiceLineBreakdown的构造函数需要引用包含它的匿名InvoiceLineModel

我理解不引用子代的父代有很好的论据,但有没有任何方法可以使用Object Initializers]实现上面的嵌套声明,或者我只需要显式声明所有对象,然后再组成Invoice Header?

使用变量引用。

下面是一个完整的例子:

using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var ihm = new 
{
InvoiceLineModels = new List<Object>
{
new {
Test = 1,
//ihm = ihm Can't be used here until the declaration is completed nor can this be used.
}
}
};
//ihm is available here 
Console.WriteLine(ihm.ToString());
}
}

看来你应该把流程分开;从db加载子级,然后将它们添加到要返回的列表中,该列表可以存储在ihm中。在查询过程中使用let语法可以实现同样的功能。

总之。分配等的POF在哪里?祝好运

最新更新