Elegant way of reading a child property of an object

前端 未结 11 1190
半阙折子戏
半阙折子戏 2020-12-24 02:19

Say you are trying to read this property

var town = Staff.HomeAddress.Postcode.Town;

Somewhere along the chain a null could exist. What wo

11条回答
  •  攒了一身酷
    2020-12-24 02:42

    I came up with the same solution as Ani's some time ago, see this blog post for details. While elegant, it's very inefficient...

    var town = Staff.NullSafeEval(s => s.HomeAddress.Postcode.Town, "(N/A)");
    

    A better solution IMHO is the one suggested in this CodeProject article:

    string town = Staff.With(s => s.HomeAddress)
                       .With(a => a.Postcode)
                       .With(p => p.Town);
    

    The only thing I don't like with this solution is the name of the extension method, but it can easily be changed...

提交回复
热议问题