数据集函数在被赋值之前使用

时间:2015-08-13 21:35:00

标签: asp.net .net vb.net

我正在尝试纠正ASP.NET应用程序抛出的一些警告。我看到很多类型的警告

"Warning    1   Variable 'ListPostFrom' is used before it has been assigned 
a value. A null reference exception could result at runtime."

来自以下的功能:

    Public Function ListPostFrom(Optional ByVal SortCol As String = "dept", Optional ByVal SortOrder As String = "ASC", _
                            Optional ByVal ActiveOnly As Boolean = False) As DataSet

    Try
        Dim objDepartmentDA As New DepartmentDA

        'Fill dataset
        ListPostFrom = objDepartmentDA.ListPostFrom(SortCol, SortOrder, ActiveOnly)

    Catch ex As Exception

        'Dataset may be empty
        Return ListPostFrom    << This is the line with the error

    End Try

    'Return dataset
    Return ListPostFrom

End Function

我的问题是,纠正这类警告的最佳方法是什么?

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:-1)

这样你就有了一个Nothing(赋值)的数据集,所以如果它没有填充,那么它返回Nothing所以只需在使用之前检查它。由于函数返回了一些东西,你需要确保它有一个值。

Public Function ListPostFrom(Optional ByVal SortCol As String = "dept", Optional ByVal SortOrder As String = "ASC", _
                        Optional ByVal ActiveOnly As Boolean = False) As DataSet
 Dim result As DataSet = Nothing
 Try
    Dim objDepartmentDA As New DepartmentDA
    'Fill dataset
    result = objDepartmentDA.ListPostFrom(SortCol, SortOrder, ActiveOnly)
 Catch ex As Exception
    'do nothing  
 End Try
 Return result 'may be nothing
End Function

用法:

Dim ds = ListPostFrom()
If Not ds Is Nothing Then
   'use ds in here
End If