使用其位置从ENUM获取值 [英] Gettting value from ENUM using its position

查看:78
本文介绍了使用其位置从ENUM获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我已经宣布这样的枚举

  enum  monthToVal 
{
JAN = 1 ,FEB,MAR,APR,MAY,JUN,JUL,AUG ,SEP,OCT,NOV,DEC
}



是否可以从枚举中获取FEB?



string monthName = monthToVal(2)或monthToVal(DateTime.Now.Month)或类似的内容?



如果我传递位置值,那么我想从中获得相应的项目。

我想知道为什么我之前没有使用枚举....



问候,

RK

解决方案

你可以用这种方式玩枚举:

< pre lang =c#> monthToVal value =(monthToVal) 2 ; // 值将保留monthToVal.FEB
string name = monthToVal.ToString( g); // 名称将保留FEB

请参阅 Enum.GetName方法 [ ^ ]。

您可以执行以下操作,从值中获取Enum常量名称。

 Enum.GetName(< span class =code-keyword> typeof (monthToVal), 2 ); 


您没有查看文档 [ ^ ],是吗?


Hi Guys,

I have declared enum like this

enum monthToVal
        {
            JAN=1,FEB,MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
        }


Is it possible to take FEB from enum?

string monthName = monthToVal(2) or monthToVal(DateTime.Now.Month) or something like this?

Like if I pass position value then I want respective item from it.
I wonder why I did'nt use enum earlier....

Regards,
RK

解决方案

You can play with enums this way:

monthToVal value = (monthToVal)2; // value will hold monthToVal.FEB
string name = monthToVal.ToString("g"); // name will hold "FEB"


Refer- Enum.GetName Method[^].
You can do like below to get the Enum constant name from value.

Enum.GetName(typeof(monthToVal), 2);


You did not check out the documentation[^], did you?


这篇关于使用其位置从ENUM获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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