对象初始化程序 - 将字段设置为其他字段不能按预期工作,为什么?

Eri*_*rix 0 c# linq

我有一些看起来像这样的代码:

List<ListBoxItem> items = (
    from String file in e.Result
    select new ListBoxItem {
        Content = file.Split('\\').Last(),
        Tag = Content,
    }).ToList<ListBoxItem>();
Run Code Online (Sandbox Code Playgroud)

这里,在创建对象之后,结果不等同于

List<ListBoxItem> items = (
    from String file in e.Result
    select new ListBoxItem {
        Content = file.Split('\\').Last(),
        Tag = file.Split('\\').Last(),
    }).ToList<ListBoxItem>();
Run Code Online (Sandbox Code Playgroud)

为什么生成的对象初始化不同?

Kir*_*oll 7

除非您已Content在封闭范围内声明,否则您的代码甚至不合法.在初始化过程中,您无法引用正在初始化的对象的其他属性.


Kei*_*ith 5

柯克的回答是正确的.但是,我认为你要做的是使用你的代码更加干燥.我想这就是你要做的事情:

List<ListBoxItem> items = (from String file in e.Result
                                       let lastFile = file.Split('\\').Last()
                                       select new ListBoxItem
                                           {
                                               Content = lastFile,
                                               Tag = lastFile
                                           }).ToList<ListBoxItem>();
Run Code Online (Sandbox Code Playgroud)