2

可能重复: 当函数没有返回时,VB.NET 中没有警告

在编写以下函数时,我注意到我没有收到关于不在所有代码路径上返回值的警告。该CASE ELSE子句没有返回值,所以它应该给我一个警告。我尝试将通知级别从警告更改为错误,但它仍然没有抱怨它。

Public Function LookupOccasionGroup(ByVal occasion As GCOccasionType) As GCOccasionGroups

    Dim occasionInfo = _occasionTypes.FindByOccasionTypeID(occasion)
    If occasionInfo Is Nothing Then
        Throw New InvalidOperationException("blah blah")
    End If

    Select Case occasionInfo.OccasionGroupID

        Case GCOccasionGroups.DineIn, GCOccasionGroups.Delivery, GCOccasionGroups.CarryOut
            Return CType(occasionInfo.OccasionGroupID, GCOccasionGroups)

        Case Else
            Log.Warn("Blah Blah.")
    End Select

End Function

在此处输入图像描述

4

2 回答 2

1

您将 VB.NET 与另一种语言混淆了;在 VB.NET 中允许不分配返回值。返回值为 Nothing,与 C# 中的 default(T) 相同。这在 Visual Basic 中一直是允许的。

屏幕截图显示了另一种诊断,当您忘记声明函数返回值类型时得到的诊断。编译器现在不能再可靠地确定在没有进行赋值时要返回什么。当没有赋值时,它为 Object 下注并返回 Nothing。这可能会引发一个难以理解的 NRE 异常,抛出一个几乎没有提示真正问题所在的位置:

Function Foo()
End Function

您现在将获得:

error BC42021: Function without an 'As' clause; return type of Object assumed.
error BC31072: Warning treated as error : Function without an 'As' clause; return type of Object assumed.
error BC42105: Function 'foo' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.

前两个错误是由同一列表中的“隐式类型;假定对象”条件生成的。第三个错误是您要查找的错误,并且警告通过更改变成了错误。当然,您实际上并不想使用它。

于 2012-10-04T18:16:50.420 回答
0

Are all the possible values of the enum contained within the first case? If so, then it is conceivable that there's enough intelligence there to believe the else will never be hit.

To test this, either add a new value to the enum, or remove one of the possible values from the first case.

于 2012-10-04T16:55:19.153 回答