开发者

object initializer - setting field to other field doesn't work as expected, why?

开发者 https://www.devze.com 2023-04-01 03:50 出处:网络
I had some code that looked like this: List<List开发者_如何学CBoxItem> items = ( from String file in e.Result

I had some code that looked like this:

List<List开发者_如何学CBoxItem> items = (
    from String file in e.Result
    select new ListBoxItem {
        Content = file.Split('\\').Last(),
        Tag = Content,
    }).ToList<ListBoxItem>();

Here, after object creation, the result is not equivalent to

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

Why are the resulting object initializations different?


Unless you have Content declared in the enclosing scope, your code is not even legal. You cannot refer to other properties of the object you are initializing while in the middle of initializing it.


Kirk's answer is correct. However, I think what you're trying to do is being more dry with your code. I think this is what you're looking to do:

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


In the line:

Tag = Content,

The Content there is not, AFAIK, relating to the .Content of the new object; that expression is resolved in the context of the rest of the code. Are you sure you don't have a .Content property/field kicking around? i.e. the equivalent of:

var tmp = Content;
select new ListBoxItem
{
    Content = file.Split('\\').Last(),
    Tag = tmp,
}).ToList<ListBoxItem>()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号