How to TryParse for Enum value?

前端 未结 14 958
终归单人心
终归单人心 2020-11-29 00:22

I want to write a function which can validate a given value (passed as a string) against possible values of an enum. In the case of a match, it should return th

14条回答
  •  攒了一身酷
    2020-11-29 00:53

    Based on .NET 4.5

    Sample code below

    using System;
    
    enum Importance
    {
        None,
        Low,
        Medium,
        Critical
    }
    
    class Program
    {
        static void Main()
        {
        // The input value.
        string value = "Medium";
    
        // An unitialized variable.
        Importance importance;
    
        // Call Enum.TryParse method.
        if (Enum.TryParse(value, out importance))
        {
            // We now have an enum type.
            Console.WriteLine(importance == Importance.Medium);
        }
        }
    }
    

    Reference : http://www.dotnetperls.com/enum-parse

提交回复
热议问题