获取枚举值的名称 [英] Get the name of Enum value

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

问题描述

我想做一个功能,我们可以得到一个EnumValue的Namevalue

例如:

  Get_Enum_ValueName(星期几,0)
 

...这将返回周日

但我的code不工作,它说的类型没有定义:

 专用功能Get_Enum_ValueName(Of T)中(BYVAL EnumName为t,BYVAL EnumValue为整数)作为字符串
    返回DirectCast([枚举] .Parse(的GetType(EnumName),EnumValue),EnumName)的ToString
端功能
 

解决方案

给定一个枚举

 公开枚举周
{
    星期一,
    星期二,
    星期三,
    星期四,
    星期五,
    星期六,
    星期日
}
 

这里的事情可以做:

 静态无效的主要(字串[] args)
{

    //枚举为int
    INT I =(INT)Week.Thursday;

    // int值枚举;
    周天=(周)3;

    //枚举字符串
    字符串名称= Week.Thursday.ToString();
    字符串的乐趣= Enum.GetName(typeof运算(周),6);
    字符串AGH = Enum.GetName(typeof运算(周),Week.Monday);
    字符串结婚= EnumName(Week.Wednesday);

    //字符串枚举
    周易=(周)Enum.Parse(typeof运算(周),星期四);

    //枚举类型的所有值
    周[]天=(周[])Enum.GetValues​​(typeof运算(周));

    //枚举类型的所有名称
    字符串[]名称= Enum.GetNames(typeof运算(周));

}

静态字符串EnumName< T>(吨价)
{
    返回Enum.GetName(typeof运算(T),值);
}
 

I'm trying to make a function where we can get the Namevalue of a EnumValue

For example:

Get_Enum_ValueName(DayOfWeek, 0)

...This will return "Sunday".

But my code don't works, it says the type is not defined:

Private Function Get_Enum_ValueName(Of T)(ByVal EnumName As T, ByVal EnumValue As Integer) As String
    Return DirectCast([Enum].Parse(GetType(EnumName), EnumValue ), EnumName).ToString
End Function

解决方案

Given an enum

public enum Week
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

here are the things you can do:

static void Main(string[] args)
{

    // enum to int
    int i=(int)Week.Thursday;

    // int to enum;
    Week day=(Week)3;

    // enum to string
    string name=Week.Thursday.ToString();
    string fun=Enum.GetName(typeof(Week), 6);
    string agh=Enum.GetName(typeof(Week), Week.Monday);
    string wed=EnumName(Week.Wednesday);

    // string to enum
    Week apt=(Week)Enum.Parse(typeof(Week), "Thursday");

    // all values of an enum type
    Week[] days=(Week[])Enum.GetValues(typeof(Week));

    // all names of an enum type
    string[] names=Enum.GetNames(typeof(Week));

}

static string EnumName<T>(T value)
{
    return Enum.GetName(typeof(T), value);
}

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

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