How to achieve the C# 'as' keyword for value types in vb.net?

后端 未结 6 2403
无人及你
无人及你 2020-12-15 10:20

Most of our development is done in vb.net (not my choice) and one frequently used code pattern uses an \'On Error GoTo\' followed by a \'Resume Next\' so that all database f

6条回答
  •  长情又很酷
    2020-12-15 10:50

    I don't think that VB.NET has any operator that mimics the functioning of the ?? operator of C#. However, you could use the equivalent of C#'s ternary operator - The IIF function in your case:

    Admittedly ugly:

    oObject.Name = IIf(oReader.Item("Name").Equals(DBNull.Value), DirectCast(oReader.Item("Name"), String), String.Empty)
    oObject.Value = IIf(oReader.Item("Value").Equals(DBNull.Value), DirectCast(oReader.Item("Value"), Integer), -1)
    

    Please make sure to read Stephen Weatherford's post in the link I provided above which suggests a generic IIf function that infers type requirements from the provided arguments. This becomes necessary because the IIf function always returns an Object!

    A better option would be to create a function that performs this cast conditionally, rather than trying to do it in one line.

提交回复
热议问题