首页 > 解决方案 > 是否可以在 vb.net 中创建一个数组或函数集合?

问题描述

我正在编写一个非常基本的功能,该功能将入站电子邮件分类到组邮箱中,根据他们打算被谁阅读到文件夹中。这是一件愚蠢的事情,因为我们都有自己的电子邮件地址,但公司经常做愚蠢的事情!

确定“电子邮件是给谁”的标准非常复杂,所以我正在编写一系列简单的函数来返回它是否“给”特定的人

Function IsRichard(msg As Outlook.MailItem) As Boolean
    ...
End Function

Function IsTim(msg As Outlook.MailItem) As Boolean
   ...
End Function

目前,我正在一个控制功能中按顺序运行所有这些Function WhoIsItFor()。但是,这个子现在变得有点长而且笨拙,所以我想知道是否可以定义一个数组或函数集合,以便我可以按照以下方式做一些事情:


Const AllFunctions as Function () = {IsRichard, IsTim ...}

Function WhoIsItFor(msg as Outlook.MailItem) as String
    
   For Each thisFunction as Function in AllFunctions
       if thisFunction(msg) then
          return (thisFunction.name)
       end if
   next

end function

标签: arraysvb.netfunctioncollections

解决方案


您应该使用 AddressOf 运算符并使用委托 Func 定义数组类型:

Dim AllFunctions() As Func(Of Outlook.MailItem, Boolean) = {AddressOf IsRichard, AddressOf IsTim}

Function WhoIsItFor(msg As Outlook.MailItem) As String

    For Each thisFunction As Func(Of Outlook.MailItem, Boolean) In AllFunctions
        If thisFunction(msg) Then
            Return thisFunction.Method.Name
        End If
    Next
    Return Nothing
End Function

推荐阅读