Elegant way of reading a child property of an object

前端 未结 11 1250
半阙折子戏
半阙折子戏 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:36

    Can't test right now, but wouldn't something like this work?

    if (Staff??Staff.HomeAdress??Staff.HomeAddress.Postcode??Staff.HomeAddress.Postcode.Town != null)
    {
        var town = Staff.HomeAddress.Postcode.Town
    }
    

提交回复
热议问题