如何检测函数是否需要返回值

时间:2014-02-20 15:37:13

标签: vb.net function return-value

我想知道是否可以检测函数是否需要返回值。 示例:

dim lLayer as layer

lLayer = CreateLayer("Test")
CreateLayer("Test2")

private function CreateLayer(LayerName as string) as layer
    [...]
    if functionNeedReturn then
        return selectLayer(LayerName)
    else
        return nothing
    end if
end function

CreateLayer的第一次调用应返回一个值(所以if为true),第二次调用应该不返回任何值。

有可能做这样的事吗?也许使用system.reflection命名空间......

2 个答案:

答案 0 :(得分:1)

您必须创建另一个函数/属性,以确定CreateLayer是否会返回某些内容。然后由调用者首先调用它,除非他不关心接收空值。

然而,由于你的方法是私密的,我很难弄清楚你想要保护自己的东西,在这里。

答案 1 :(得分:0)

如果我误解了你的问题,请原谅我。在vb.net中有一个static关键字,其中“指定一个或多个声明的局部变量将继续存在并在终止声明它们的过程后保留其最新值”

因此,如果只允许通过CreateLayer创建一个图层实例,则可以执行以下操作:

Private Function CreateLayer(name As String, Optional ByRef returnValueIsNull As Boolean = False) As Layer

    Static isCreated As Boolean

    If (isCreated) Then
        returnValueIsNull = True
        Return Nothing
    Else
        '[...]
        isCreated = True
        returnValueIsNull = False
        Return SelectLayer(name)
    End If

End Function

'Or reversed:

Private Function TryCreateLayer(name As String, Optional ByRef result As Layer = Nothing) As Boolean

    Static isCreated As Boolean

    If (Not isCreated) Then
        '[...]
        isCreated = True
        result = SelectLayer(name)
        Return True
    End If

    Return False

End Function

现在,如果允许创建一个受名称约束的多个图层,可以按以下方式执行:

Private Function CreateLayer(name As String, Optional ByRef created As Boolean = False) As Layer

    Static cache As Dictionary(Of String, Layer)

    If (cache Is Nothing) Then
        cache = New Dictionary(Of String, Layer)
    End If

    Dim item As Layer = Nothing

    If (cache.TryGetValue(name, item)) Then
        created = False
    Else
        '[...]
        created = True
        item = SelectLayer(name)
        cache.Add(name, item)
        Return SelectLayer(name)
    End If

    Return item

End Function

'Or reversed:

Private Function TryCreateLayer(name As String, Optional ByRef result As Layer = Nothing) As Boolean

    Static cache As Dictionary(Of String, Layer)

    If (cache Is Nothing) Then
        cache = New Dictionary(Of String, Layer)
    End If

    If (Not cache.TryGetValue(name, result)) Then
        '[...]
        result = SelectLayer(name)
        cache.Add(name, result)
        Return True
    End If

    Return False

End Function