C#数字枚举值的字符串 [英] C# numeric enum value as string

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

问题描述

我有以下枚举:

public enum Urgency {
    VeryHigh = 1,
    High     = 2,
    Routine  = 4
}

我可以卖到一个<强>枚举价值为字符串是这样的:

I can fetch an enum "value" as string like this:

((int)Urgency.Routine).ToString() // returns "4"  

请注意:这是不同的:

Urgency.Routine.ToString() // returns "Routine"
(int)Urgency.Routine       // returns 4

有没有一种方法,我可以创建一个扩展类或静态utliity类,这将提供一些语法糖吗? :)

Is there a way I can create an extension class, or a static utliity class, that would provide some syntactical sugar? :)

推荐答案

您应该只能够使用枚举的ToString方法的重载给它一个格式字符串,这将打印出了枚举作为一个字符串的值。

You should just be able to use the overloads of Enums ToString method to give it a format string, this will print out the value of the enum as a string.

public static class Program
{
    static void Main(string[] args)
    {
        var val = Urgency.High;
        Console.WriteLine(val.ToString("D")); 
    }
}

public enum Urgency 
{ 
    VeryHigh = 1,
    High = 2,
    Low = 4
}

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

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