我遇到了以下问题。我最近激活了'Option Strict On',现在我的LINQ查询出错了。 From e As TEnum
返回以下错误:
Option Strict On禁止从'Object'到'TEnum'
的隐式转换
有谁知道如何解决这个问题?
Public Module SelectItemPandEnumExtension
<System.Runtime.CompilerServices.Extension()> _
Public Function ToSelectListEnum(Of TEnum)(enumObj As TEnum) As SelectList
Dim values = From e As TEnum In [Enum].GetValues(GetType(TEnum))
Select New With {.Id = e, .Name = e.ToString()}
Return New SelectList(CType(values, Collections.IEnumerable), "Id", "Name", enumObj)
End Function
End Module
答案 0 :(得分:1)
我想你想要这个:
Dim values As IEnumerable = From e As TEnum In CType([Enum].GetValues(GetType(TEnum)), TEnum())
Select New With {.Id = e, .Name = e.ToString()}
Return New SelectList(values, "Id", "Name", enumObj)
GetValues返回一个Object(),但另外还需要定义值的类型。这意味着您在创建选择列表时不必键入它。 (好吧,假设你也有推断选项)
答案 1 :(得分:1)
我必须删除As TEnum
。
答案 2 :(得分:0)
[Enum].GetValues
会返回Object()
,但您应该能够拥有一个临时的强类型列表:
<System.Runtime.CompilerServices.Extension()> _
Public Function ToSelectListEnum(Of TEnum)(enumObj As TEnum) As SelectList
Dim values = From e As TEnum In New List(of TEnum)([Enum].GetValues(GetType(TEnum)))
Select New With {.Id = e, .Name = e.ToString()}
Return New SelectList(CType(values, Collections.IEnumerable), "Id", "Name", enumObj)
End Function