.net vb或c#If(MethodReturningCollection).当方法不返回任何值时,MethodofC
本文关键字:返回 任何值 MethodofC 方法 vb c#If MethodReturningCollection net | 更新日期: 2023-09-27 18:27:31
有没有一种方法可以在一行中实现这一点,out调用函数两次,out将其存储为局部变量
下面是我使用的函数类型的示例。函数的设计是在它为空时不返回任何内容。
我所知道的当前选项
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
如果您使用的是最新版本的C#/VB,则可以使用null条件运算符(?.
)。
如果CreateObjectList()
返回null
/nothing
,则表达式CreateObjectList()?.Count
将返回null
/nothing
。返回值的类型将是Nullable<int>
,您可以直接将其与int
进行比较,并获得预期结果(您在标题中提到了C#,所以我将使用C#,因为我的VB不是很好):
if(CreateObjectList()?.Count > 5)
{
// do something
}
顺便说一下,CreateObjectList
的当前实现永远不会返回null
——returnlist
在第一行初始化为一个新实例。
为了确保它总是以这种方式运行,您可以使用代码契约并添加以下内容:
Contract.Ensures(Contract.Result<string>() != null);