13
Public Enum Fruit
Red_Apple = 1
Oranges
Ripe_Banana
End Enum
Private Sub InitCombosRegular()
Dim d1 As New Dictionary(Of Int16, String)
For Each e In [Enum].GetValues(GetType(Fruit))
d1.Add(CShort(e), Replace(e.ToString, "_", " "))
Next
ComboBox1.DataSource = d1.ToList
ComboBox1.DisplayMember = "Value"
ComboBox1.ValueMember = "Key"
ComboBox1.SelectedIndex = 0
End Sub
'This fails
Dim combo1 = DirectCast(ComboBox1.SelectedValue, Fruit) ' Fails
'these both work
Dim combo2 = DirectCast(CInt(ComboBox1.SelectedValue), Fruit) 'works
Dim combo3 = CType(ComboBox1.SelectedValue, Fruit) 'works
为什么CType
工作和DirectCast
不具有相同的语法?然而,如果我之前,我DirectCast
投的selectedValue
到int
,然后它Directcast和Ctype与枚举的区别
问候
_Eric
感谢。对此最好的做法是什么?显式地将selectedValue转换为int和directcast(#2),或者只是Ctype(#3) – Eric 2009-10-13 19:52:16
每当我处理枚举值时,我更喜欢CType – JaredPar 2009-10-13 19:54:32
@Eric:当对象是给定类型时应该使用DirectCast ,并且您正在将其转换为该类型。一个字符串不是一个枚举,也不是一个整数。如果您想先将其转换为整数,这可能会让您的代码更加清晰,但使用DirectCast只会让事情混淆不清。 – jmoreno 2017-06-15 16:46:22