简体   繁体   English

如何缩短If ... Else ...语句以检查Date的状态?

[英]How would I shorten this If… Else… statement to check the state of a Date?

I am a C# programmer but dabbling in VB.Net because everybody else in my team uses it. 我是C#程序员,但涉足VB.Net,因为团队中的其他所有人都在使用它。 In the interests of professional development I would like to shrink the following If... Else... statement. 为了职业发展的利益,我想缩小以下If ... Else ...语句。

If cmd.Parameters("@whenUpdated").Equals(DBNull.Value) Then
    item.WhenUpdated = Nothing
Else
    item.WhenUpdated = cmd.Parameters("@whenUpdated").Value
End If

I appreciate examples are already available however I can not get it working for this specific case. 我很欣赏示例,但我无法在特定情况下使用它。

Cheers, Ian. 干杯,伊恩。

使用If作为函数而不是语句:

item.WhenUpdated = If(cmd.Parameters("@whenUpdated").Equals(DBNull.Value), cmd.Parameters("@whenUpdated").Value, Nothing)

Similar to the ternary operator in C#, VB has the IIF function . 与C#中的三元运算符类似,VB具有IIF函数

item.WhenUpdated = IIF(cmd.Parameters("@whenUpdated").Equals(DBNull.Value),
                            cmd.Parameters("@whenUpdated").Value, 
                            Nothing)

If the first argument (the boolean expression) evaluates to true, then the second argument is returned from the function. 如果第一个参数(布尔表达式)的计算结果为true,则从函数返回第二个参数。 If the first argument is false, then the third argument is returned. 如果第一个参数为false,则返回第三个参数。

item.WhenUpdated = Nothing
If cmd.Parameters("@whenUpdated").Equals(DBNull.Value) Then
    item.WhenUpdated = cmd.Parameters("@whenUpdated").Value
End If

Only 1 line, but still shorter. 只有1行,但仍然更短。

The IF function is definitely the shortest, but not the most readable. IF函数绝对是最短的,但不是最易读的。

One less line 少一行

item.WhenUpdated = Nothing
If cmd.Parameters("@whenUpdated").Equals(DBNull.Value) Then
    item.WhenUpdated = cmd.Parameters("@whenUpdated").Value
End If

Use the operator If(...) if you want short-circuiting behavior. 如果需要短路行为,请使用运算符If(...)。

Use the function IIf(...) if you don't want short-circuiting behavior. 如果您不想发生短路行为,请使用函数IIf(...)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM