从C#中的枚举获取字符串名称 [英] Get String Name from Enum in C#

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

问题描述

我已声明以下枚举

public enum State
    {
        KARNATAKA = 1,
        GUJRAT = 2,
        ASSAM = 3,
        MAHARASHTRA = 4,
        GOA = 5
    }

从外部来源,我得到的State值为1或2或3或4或5。

From external sources, I get the State values as either 1 or 2 or 3 or 4 or 5.

根据我得到的值,我需要查找该枚举并获取其字符串。

Based on the value i get, I need to look up this enum and get its string.

对于Ex:如果输入值为1,则需要返回KARNATAKA作为串。同样,如果输入值为5,则需要将GOA作为字符串返回。

For Ex: If the input value is 1, I need to return KARNATAKA as string. Similarly, If the input value is 5, I need to return GOA as string.

有没有一种简便的方法可以使用CASE或IFELSE来获取字符串。

Is there a easy way to get the string with out using CASE or IFELSE.

推荐答案

您可以简单地使用 nameof 表达式以获得枚举的名称,枚举值,属性,方法,

You can simply use the nameof expression to get the name of an enum, enum value, property, method, classname, etc.

使用nameof表达式的最快的编译时解决方案。

The fastest, compile time solution using nameof expression.

返回枚举的文字。

public enum MyEnum {
    CSV,
    Excel
}

// calling code
string enumAsString = nameof(MyEnum.CSV) // enumAsString = "CSV"

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

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