获取具有描述属性的枚举值 [英] Getting value of Enum with Description Attribute of it

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

问题描述

  public enum MyEnum 
{
Name1 = 1,
[描述(这是另一个)]
HereIsAnother = 2,
[描述(最后一个)]
LastOne = 3
}

我的价值为最后一个是3



返回的代码是什么?

解决方案

你可以这样做

  int lastOneValue =(int)MyEnum.LastOne; 

此代码返回值2而不是LastOne

  string lastOneString = MyEnum.LastOne.ToString(); 

此代码返回LastOne作为字符串值

  MyEnum mynum = MyEnum.LastOne; 

此代码创建新对象 MyEnum 和将其值设置为LastOne


I have an enum with Description attributes like this:

public enum MyEnum
{
    Name1 = 1,
    [Description("Here is another")]
    HereIsAnother = 2,
    [Description("Last one")]
    LastOne = 3
}

I have value of "Last one" that is 3

What is the code that return that?

解决方案

You can do it like this

int lastOneValue = (int) MyEnum.LastOne;

This code returns the value 2 instead of "LastOne"

string lastOneString = MyEnum.LastOne.ToString();

This code returns "LastOne" as a string value

MyEnum mynum = MyEnum.LastOne;

This code creates new object of MyEnum and sets his value to 'LastOne'

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

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