【问题标题】:Directcast & Ctype differences with enumsDirectcast 和 Ctype 与枚举的区别
【发布时间】:2010-12-06 10:34:39
【问题描述】:
 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,那么它可以工作

问候

_埃里克

【问题讨论】:

    标签: vb.net directcast ctype


    【解决方案1】:

    之所以如此,是因为CTypeDirectCast是根本不同的操作。

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

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

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

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

    【讨论】:

    • 谢谢。这方面的最佳做法是什么?将 selectedValue 显式转换为 int 和 directcast(#2),或者只是 Ctype(#3)
    • 在处理枚举值时我更喜欢 CType
    • @Eric:当对象属于给定类型并且您将其强制转换为该类型时,应使用 DirectCast。字符串不是枚举,也不是整数。如果您想先转换为整数,那可能会使您的代码更清晰,但使用 DirectCast 只会让事情变得混乱。
    猜你喜欢
    • 2011-03-04
    • 2013-10-27
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多