如何检索给定名称的Enum成员 [英] How to retrieve an Enum member given its name

查看:41
本文介绍了如何检索给定名称的Enum成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很容易得到下面的枚举

It's very easy I have the following Enum

Public Enum TCheckStatus
        Checked
        NotChecked
        Indeterminate 
    End Enum

我想在枚举中找到给定名称的索引,最好的方法是什么!!

I want to get the Index of the given name found in the enum, what's the best way?!!

例如:

假设我有"NotChecked"字符串,我希望输出为1

Suppose I have "NotChecked" string , I want the output to be 1

推荐答案

您正在寻找枚举GetNames .它检索指定枚举中常量名称的数组.

You are looking for Enum.GetNames. It retrieves an array of the names of the constants in a specified enumeration.

Dim notCheckedStatus  = DirectCast([Enum].Parse(GetType(TCheckStatus), "NotChecked"), TCheckStatus)
Dim allStatusNames    = [Enum].GetNames(GetType(TCheckStatus))
Dim indexOfNotChecked = Array.IndexOf(AllStatusNames, "NotChecked") '=1'

  1. line:将 string 变量解析为枚举值
  2. line:将给定枚举类型的所有枚举值返回为 Array
  3. line:返回该 Array
  4. 中给定枚举值的索引
  1. line: parses a string variable to an enum-value
  2. line: returns all enum-values of a given enum-type as Array
  3. line: returns the index of a given enum-value in that Array

当然要解决您的问题,您只需要这样做:

Of course to solve your question you only need this:

Array.IndexOf([Enum].GetNames(GetType(TCheckStatus)), "NotChecked") 

这篇关于如何检索给定名称的Enum成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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