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运行时能够找到词法转换来解决这个问题

这里有一个关于差异的体面讨论:


谢谢。这方面的最佳做法是什么?显式强制转换将所选的值转换为int和directcast(#2),或仅转换为Ctype(#3)。每当我处理enum时,我更喜欢Ctypevalues@Eric:当对象为给定类型且您正在将其强制转换为该类型时,应使用DirectCast。字符串不是枚举,也不是整数。如果您想先强制转换为整数,这可能会使代码更清晰,但使用DirectCast只会混淆问题。
 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