Enum value to string

前端 未结 6 1826
无人共我
无人共我 2021-02-06 21:59

Does anyone know how to get enum values to string?

example:

private static void PullReviews(string action, HttpContext context)
{
    switch (action)
            


        
6条回答
  •  庸人自扰
    2021-02-06 22:37

    This is just for the fun of it, but what if you used a dictionary of delegates? I realize that you have a completely different approach, but dictionary-izing might actually work better for what you're trying to accomplish, especially since it provides a high degree of modularity, as opposed to a mondo-switch construct (although I have to admit, your enum has only 2 members so its a moot issue). Anyways, I just wanted to air a different way to do things...

    The dictionary-based approach would kind of look like this:

    namespace ConsoleApplication1
    {
        public enum ProductReviewType
        {
            Good,
            Bad
        }
    
        public static class StringToEnumHelper
        {
            public static ProductReviewType ToProductReviewType(this string target)
            {
                // just let the framework throw an exception if the parse doesn't work
                return (ProductReviewType)Enum.Parse(
                  typeof(ProductReviewType), 
                  target);
            }
        }
    
        class Program
        {
    
            delegate void ReviewHandler(HttpContext context);
    
            static readonly Dictionary 
                pullReviewOperations = 
                  new Dictionary()
                {
                    {ProductReviewType.Good, new ReviewHandler(PullGoodReviews)},
                    {ProductReviewType.Bad, new ReviewHandler(PullBadReviews)}
                };
    
            private static void PullGoodReviews(HttpContext context)
            {
                // actual logic goes here...
                Console.WriteLine("Good");
            }
    
            private static void PullBadReviews(HttpContext context)
            {
                // actual logic goes here...
                Console.WriteLine("Bad");
            }
    
            private static void PullReviews(string action, HttpContext context)
            {
                pullReviewOperations[action.ToProductReviewType()](context);
            }
    
            static void Main(string[] args)
            {
                string s = "Good";
                pullReviewOperations[s.ToProductReviewType()](null);
    
                s = "Bad";
                pullReviewOperations[s.ToProductReviewType()](null);
    
                // pause program execution to review results...
                Console.WriteLine("Press enter to exit");
                Console.ReadLine();
            }
        }
    }
    

提交回复
热议问题