与枚举的直播和Ctype差异

Eri*_*ric 13 vb.net ctype 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
Run Code Online (Sandbox Code Playgroud)

为什么CType工作和DirectCast语法不一样?然而,如果我在我之前投了selectedValue一个,那么它是有效的intDirectCast

问候

_Eric

Jar*_*Par 21

原因是因为CType并且DirectCast是根本不同的操作.

DirectCast是VB.Net中的一个转换机制,它只允许CLR定义的转换.它比C#版本的转换更具限制性,因为它不考虑用户定义的转换.

CType是一种词法铸造机制.它考虑了CLR规则,用户定义的转换和VB.Net定义的转换.简而言之,它将尽一切可能为对象创建到指定类型的有效转换.

在这种特殊情况下,您尝试将值转换为没有CLR定义转换的Enum,因此它失败了.然而,VB.Net运行时能够找到词法转换来满足该问题.

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