Get int value from enum in C#

前端 未结 28 1924
臣服心动
臣服心动 2020-11-22 04:58

I have a class called Questions (plural). In this class there is an enum called Question (singular) which looks like this.

public e         


        
28条回答
  •  无人及你
    2020-11-22 05:37

    To ensure an enum value exists and then parse it, you can also do the following.

    // Fake Day of Week
    string strDOWFake = "SuperDay";
    
    // Real Day of Week
    string strDOWReal = "Friday";
    
    // Will hold which ever is the real DOW.
    DayOfWeek enmDOW;
    
    // See if fake DOW is defined in the DayOfWeek enumeration.
    if (Enum.IsDefined(typeof(DayOfWeek), strDOWFake))
    {
        // This will never be reached since "SuperDay"
        // doesn't exist in the DayOfWeek enumeration.
        enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWFake);
    }
    // See if real DOW is defined in the DayOfWeek enumeration.
    else if (Enum.IsDefined(typeof(DayOfWeek), strDOWReal))
    {
        // This will parse the string into it's corresponding DOW enum object.
        enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWReal);
    }
    
    // Can now use the DOW enum object.
    Console.Write("Today is " + enmDOW.ToString() + ".");
    

提交回复
热议问题