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

后端 未结 6 2396
无人及你
无人及你 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:45

    Edit

    Sorry for sprouting such nonsense. I relied on a posting by Paul Vick (then head of the VB team) rather than the MSDN and don't have Windows installed to test the code.

    I'll still leave my posting – heavily modified (refer to the edit history to read the wrong original text) – because I find the points still have some merit.

    So, once again, three things to recap:

    1. For reference types, C#'s as is directly modelled by TryCast in VB.

      However, C# adds a little extra for the handling of value types via unboxing (namely the possibilities to unbox value types to their Nullable counterpart via as).

    2. VB 9 provides the If operator to implement two distinct C# operators: null coalescing (??) and conditional (?:), as follows:

        ' Null coalescing: '
        Dim result = If(value_or_null, default_value)
    
        ' Conditional operator: '
        Dim result = If(condition, true_value, false_value)
    

    Unlike the previous IIf function these are real short-circuited operators, i.e. only the necessary part will be executed. In particular, the following code will compile and run just fine (it wouldn't, with the IIf function, since we could divide by zero):

        Dim divisor = Integer.Parse(Console.ReadLine())
        Dim result = If(divisor = 0, -1, 1 \ divisor)
    
    1. Don't use VB6 style error handling (On Error GoTo … or On Error Resume [Next]). That's backwards compatibility stuff for easy VB6 conversion. Instead, use .NET's exception handling mechanisms like you would in C#.

提交回复
热议问题