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
不具有相同的语法?然而,如果我投 selectedValue
到 int
我之前DirectCast
,然后它工作问候
_埃里克
最佳答案
原因是因为CType
和 DirectCast
是根本不同的操作。DirectCast
是 VB.Net 中的一种转换机制,它只允许 CLR 定义的转换。它比 C# 版本的强制转换更具限制性,因为它不考虑用户定义的转换。CType
是一个词法转换机制。它考虑 CLR 规则、用户定义的转换和 VB.Net 定义的转换。简而言之,它会做任何可能的事情来为一个对象创建一个指定类型的有效转换。
在这种特殊情况下,您试图将一个值转换为一个没有 CLR 定义的转换的枚举,因此它失败了。然而,VB.Net 运行时能够找到一个词法转换来满足这个问题。
关于差异的体面讨论存在于此处:
关于vb.net - Directcast 和 Ctype 与枚举的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1562210/