使用LINQ获取枚举的名称/值对的问题[VB 2010] [英] Problem with obtaining name/value pair of enumeration with LINQ [VB 2010]

查看:100
本文介绍了使用LINQ获取枚举的名称/值对的问题[VB 2010]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用LINQ获取键入文本框的枚举名称/值对。名称可以,但是当LINQ达到值时,它会抛出错误:""从字符串转换""黑色"输入'Integer'无效"。我已经读过,如果我想获得一个值,那么我必须使用转换函数。如何解决这个问题?

这里的代码(按钮的点击事件):


I'm trying to obtain name/value pair of enumeration typed into text box with LINQ. It's OK with name, but when LINQ reaches values, it throws error: "Conversion from string "Black" to type 'Integer' is not valid". I have read that if I want to obtain a value, then I gotta use conversion function. How to solve this problem?


Here's code (button's Click event):

Private Sub GetEnums(ByVal sender As Object, ByVal e As RoutedEventArgs)

        lstEnums.Items.Clear()

        Dim typeName = Type.GetType(txtEnum.Text)
        Dim enums = From en In typeName.GetEnumNames
                    Select Name = en.ToString, Index = CInt(en)

        enums.ToList.ForEach(
            Sub(en)
                lstEnums.Items.Add(
                        String.Format("Value: {0} => Index: {1}", en.Index, en.Name))
            End Sub)

End Sub

推荐答案

Hi Motaro,

类型.GetEnumNames 返回一个包含枚举名称的字符串数组,因此异常是正确的,在这种情况下我们无法将字符串值转换为整数。 span style =""> 解决方法是调用 Type.GetEnumValues 返回所有枚举值,然后调用 类型.GetEnumName(object) 检索枚举名称或调用object.ToString以获取枚举值的名称。 有关详细信息,请参阅以下代码:

Type.GetEnumNames returns a string array that contains enumeration names, so the exception is correct that we cannot convert a string value to integer in this case.   The workaround is to call Type.GetEnumValues which returns all the enumeration values and then call Type.GetEnumName(object) to retrieve the enum name or call object.ToString to get the enum value’s name.  For detail, please see the following codes:

==============================================

Dim enums = From en typeName.GetEnumValues

Dim enums = From en In typeName.GetEnumValues

选择 Name = typeName.GetEnumName(en),Index = CInt (en)

            Select Name = typeName.GetEnumName(en), Index = CInt(en)

Dim enums2 = 来自 en typeName.GetEnumValues

Dim enums2 = From en In typeName.GetEnumValues

选择名称= en.ToString(),索引= CInt (zh-CN )

             Select Name = en.ToString(), Index = CInt(en)

===================================== =========

周末愉快!

最好的问候,
灵芝


这篇关于使用LINQ获取枚举的名称/值对的问题[VB 2010]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆