我有以下代碼:如何將這兩行重構爲一條語句?
// TryGetAttributeValue returns string value or null if attribute not found
var attribute = element.TryGetAttributeValue("bgimage");
// Convert attribute to int if not null
if (attribute != null) BgImage = convert.ToInt32(attribute);
我不喜歡的事情是,我要創建一個臨時變量,attribute
,爲了測試它是否null
與否,然後將值賦給BgImage
變量,這是一個可空的int。
我曾希望能找到一種方法將它寫在一行上,但我無法想象。我甚至嘗試使用三元語句,但沒有得到任何好處:
if (element.TryGetAttributeValue("bgimage") != null) ? BgImage = //Convert result to int : else null;
實際上,我原來的兩行代碼可以完成這項工作。我只是希望把它削減到一行。但是,如果有人知道如何去做我想做的事情,我很樂意學習。
你解析像XML? –
'TryGetAttributeValueAsInt'擴展名? –
@SergeyBerezovskiy是的,我是。 BgImage屬性可以爲null,也可以爲int,包括零。 – Kevin