2014-02-28 21 views
3

我有以下代碼:如何將這兩行重構爲一條語句?

// 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; 

實際上,我原來的兩行代碼可以完成這項工作。我只是希望把它削減到一行。但是,如果有人知道如何去做我想做的事情,我很樂意學習。

+0

你解析像XML? –

+2

'TryGetAttributeValueAsInt'擴展名? –

+0

@SergeyBerezovskiy是的,我是。 BgImage屬性可以爲null,也可以爲int,包括零。 – Kevin

回答

3

我建議你使用Linq to Xml解析XML(可根據您的嘗試,你有BgImage爲空整數):

BgImage = (int?)element.Attribute("bgimage"); 

您也可以指定一些默認值,如果BgImage不能爲空:

BgImage = (int?)element.Attribute("bgimage") ?? 0; 
+1

這對我來說很好。我根本不必使用「TryGetAttribute」方法,而且我得到了我期待的結果。只要定時器啓動,我會將其標記爲答案。謝謝! – Kevin

2

假設TryGetAttributeValue返回string你可以做類似

BgImage = convert.ToInt32(element.TryGetAttributeValue("bgimage") ?? "-1") 

如果該屬性不存在,則會將BgImage設置爲默認值(-1)。如果你希望有BgImage設置爲null當沒有bgimage屬性,那麼它變得有點笨重

BgImage = element.TryGetAttributeValue("bgimage") != null ? 
    convert.ToInt32(element.TryGetAttributeValue("bgimage")) : (int?)null; 
+0

我假設'BgImage'應該爲null,如果屬性爲null,則不應該爲-1。 – Lee

+0

'TryGetAttributeValue'返回一個字符串,如果找不到,則返回'null'。 BgColor可以是一個int,包括零或一個'null'值。 – Kevin

+0

@KevinJ所以在無法找到屬性的情況下,您更願意將'BgImage'設置爲'null'? – James