.net vb或c#If(MethodReturningCollection).MethodofCollection错误,当方法没有返回任何内容时

时间:2015-12-18 21:34:28

标签: c# .net vb.net collections

有没有办法在单行中执行此操作而不调用该函数两次,而不将其存储为局部变量?

以下是我正在使用的函数类型的示例。函数的设计在空的时候不返回任何内容。

我知道的当前选项

if not createobjectlist(0) is nothing andalso createobjectlist(0).count >5 then
    do stuff
end if

但是这个函数调用两次我想避免的。

dim tmplist as list(of object) = createobjectlist(0)

if not tmplist is nothing andalso tmplist.count > 5 then

end if

示例函数

Public Function CreateObjectList(byval numtocreate as object) as list(of object)
    Dim returnlist as new list(of ojbect) 
    for i = 0 to numtocreate
        Dim testobject as ojbect = nothing
        returnlist.add(testobject)
    next

    if returnlist.count < 1 then
        returnlist = nothing
    end if

    return returnlist
End Function

1 个答案:

答案 0 :(得分:2)

如果您使用的是最新版本的C#/ VB,则可以使用null-conditional operators?.)。

如果CreateObjectList()?.Count返回null / nothing,则CreateObjectList()表达式将返回null / nothing。返回值的类型为Nullable<int>,您可以直接与int进行比较并获得预期结果(您在标题中提到了C#,因此我将使用C#,因为我的VB不是很好):

if(CreateObjectList()?.Count > 5)
{
    // do something
}

顺便说一句,您当前的CreateObjectList实现永远不会返回null - returnlist在第一行初始化为新实例。

要确保它始终采用这种方式,您可以使用code contracts并添加以下内容:

Contract.Ensures(Contract.Result<string>() != null);