vb .net缩短if语句

时间:2011-09-29 01:20:46

标签: vb.net

我正在努力让这个更干净......我知道有很多关于If语句的快捷方式,但我不知道什么是最好的。

If item.RecurrenceId > 0 Then
    xmlTextWriter.WriteElementString("recordtype", "2")
ElseIf IsNothing(item.OngoingEndDate) = False Then
    xmlTextWriter.WriteElementString("recordtype", "1")
Else
    xmlTextWriter.WriteElementString("recordtype", "0")
End If

4 个答案:

答案 0 :(得分:3)

快捷方式并不总能带来更好的代码。虽然短代码可以“干净”,但它可能不像你所说的那样易读

话虽如此,只要符合你的目的,我会坚持你所拥有的。这是“干净”,但更重要的是,你明白你的目标是什么。

答案 1 :(得分:0)

我认为这不会起作用。

xmlTextWriter.WriteElementString("recordtype", If(item.RecurrenceId > 0, "2", If(IsNothing(item.OngoingEndDate) = False, "1", "0")));

答案 2 :(得分:0)

If operator就是这样:

If(item.RecurrenceId > 0, _
   xmlTextWriter.WriteElementString("recordtype", "2"), _
   If(Not IsNothing(item.OngoingEndDate), _
       xmlTextWriter.WriteElementString("recordtype", "1"), _
       xmlTextWriter.WriteElementString("recordtype", "0")))

答案 3 :(得分:0)

另一种方法是创建一个名为

的函数
GetRecordType(byval item as whatever) as int

使用if语句,确定0,1或2,然后调用

xmlTextWriter.WriteElementString("recordtype", GetRecordType(item).ToString())

这将使您的函数中的所有WriteElementString调用保持简短和甜蜜,同时仍然在提取的GetRecordType函数中保持if语句易于读取。