将枚举数组或列表传递给函数

时间:2014-03-26 15:56:42

标签: vb.net linq

我想将枚举数组与单个枚举实例进行比较。

简介

我有一个枚举类型为array \ list

的类
Public Enum InvalidEmailType
    Multiple_Updates  
    Period_Before_At_Sign
    Missing_Dot_Com
End Enum
Public Class CustomerClass
    Public CustomerName As String
    Public ErrorTypeList = [Enum].GetValues(GetType(InvalidEmailType))
    Public ErrorDescription As String
End Class

根据列表中添加的值,我想运行特定的代码。

为了做到这一点,我将整个列表与单个实例进行比较:

        If UpdateCustomer.MatchErrorType(customer.ErrorTypeList, InvalidEmailType.Trailing_Period) = True Then
            'Run Code
        End If

在函数内部,我将整个列表与单个实例进行比较。

换句话说,我遍历类中的整个列表并检查值是否存在:

Public Shared Function MatchErrorType(CustomerErrortypeList As List(Of InvalidEmailType), EmailError As InvalidEmailType) As Boolean
    MatchErrorType = False
    Dim Found As InvalidEmailType = CustomerErrortypeList.Where(Function(match) match.ToString = EmailError.ToString).OrderByDescending(Function(match) match.ToString).FirstOrDefault()
    If Found > 0 Then
        MatchErrorType = True
    End If
End Function

以下是问题: 如何在函数参数中声明array \ list?

List(Of InvalidEmailType)不起作用,因为我收到强制转换错误

无法转换类型' EmailValidationReport.InvalidEmailType []'输入' System.Collections.Generic.List`1 [EmailValidationReport.InvalidEmailType]'

2 个答案:

答案 0 :(得分:1)

将ErrorTypeList设置为List(of InvalidEmailType)而不是数组。

Public ErrorTypeList = [Enum].GetValues(GetType(InvalidEmailType)) _
                       .Cast(of InvalidEmailType)().ToList()

Dim list = customer.ErrorTypeList.Cast(of InvalidEmailType)().ToList()
If UpdateCustomer.MatchErrorType(list, InvalidEmailType.Trailing_Period) Then
    'Run Code
End If

答案 1 :(得分:1)

由于您没有执行特定于ListArray的任何操作,因此您可以将方法签名设为IEnumerable而不是List。这应该能够处理ListArray(以及更多类型)。

Public Shared Function MatchErrorType(CustomerErrortypeList As IEnumerable(Of InvalidEmailType), EmailError As InvalidEmailType) As Boolean
    Dim Found As InvalidEmailType = CustomerErrortypeList.Where(Function(match) match.ToString = EmailError.ToString).OrderByDescending(Function(match) match.ToString).FirstOrDefault()
    MatchErrorType = (Found > 0)
End Function