Can you add to an enum type in run-time

后端 未结 6 642
甜味超标
甜味超标 2020-12-08 07:06

If I have an enum type:

public enum Sport
{
    Tennis = 0;
    Football = 1;
    Squash = 2;
    Volleyball = 3;
}

Can I somehow add durin

6条回答
  •  粉色の甜心
    2020-12-08 07:20

    The enum has a backing store, defaulting to int if you don't specify it. It is possible to directly assign values outside of the defined values:

    Sport pingPong = (Sport)4;
    

    Then you can check for it:

    if (value == (Sport)4) {}
    

    That is why you have the static function Enum.IsDefined() for checking if the actual value falls inside the expected values. Note that the function doesn't work for compound flag values.

    bool isValueDefined = Enum.IsDefined(typeof(Sport), value);
    

    EDIT: After Hans Passant's comment: You don't have to use the literal value 4. You could use anything which returns an int. For example:

    Dictionary AdditionalSports = new Dictionary();
    AdditionalSports.Add(4, "PingPong");
    
    // Usages: if
    if (AdditionalSports.ContainsKey(value))
    {
        // Maybe do something with AdditionalSports[value], i.e. "PingPong"
    }
    
    // In a switch:
    switch (value)
    {
    case default:
        // Since it won't be found in the enum-defined values
        if (AdditionalSports.ContainsKey(value))
        {
            // Maybe do something with AdditionalSports[value], i.e. "PingPong"
        }
    }
    

提交回复
热议问题