[英]Reference anonymous parent from anonymous child when declaring nested objects with Object Initializer
如果我有一組父、子、孫子類,其中孫子需要它的父作為構造函數參數,有沒有辦法仍然能夠使用嵌套的Object Initializers聲明?
例如,考慮 Invoice Header,Invoice Line,Invoice Line 細分:
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
的引用。
我很欣賞有很好的 arguments 不引用來自孩子的父母,但是有沒有辦法使用 Object Initializers] 來實現上面的嵌套聲明,或者我只需要顯式聲明所有對象,然后再編寫發票 ZBF50D2ZE6611E6D70A7?
使用變量引用。
這是一個完整的例子:
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 在哪里。祝你好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.