Vb.net Directcast&;Ctype与枚举的差异
为什么Vb.net Directcast&;Ctype与枚举的差异,vb.net,directcast,ctype,Vb.net,Directcast,Ctype,为什么CType可以工作,而DirectCast不能使用相同的语法?但是,如果我在DirectCast之前将selectedValue转换为int,那么它就可以工作了 问候 _Eric原因在于CType和DirectCast是根本不同的操作 DirectCast是VB.Net中的一种强制转换机制,它只允许CLR定义的转换。由于它不考虑用户定义的转换,所以它比C版本的铸造更具限制性。p> CType是一种词法转换机制。它考虑CLR规则、用户定义的转换和VB.Net定义的转换。简而言之,它将尽一切可
CType
可以工作,而DirectCast
不能使用相同的语法?但是,如果我在DirectCast
之前将selectedValue
转换为int
,那么它就可以工作了
问候
_Eric原因在于
CType
和DirectCast
是根本不同的操作
DirectCast
是VB.Net中的一种强制转换机制,它只允许CLR定义的转换。由于它不考虑用户定义的转换,所以它比C版本的铸造更具限制性。p>
CType
是一种词法转换机制。它考虑CLR规则、用户定义的转换和VB.Net定义的转换。简而言之,它将尽一切可能为对象创建到指定类型的有效转换
在这种特殊情况下,您尝试将值转换为没有CLR定义的转换的枚举,因此它失败。然而,VB.Net运行时能够找到词法转换来解决这个问题
这里有一个关于差异的体面讨论:
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