Initial Value of an Enum

前端 未结 10 585
陌清茗
陌清茗 2020-12-08 01:51

I have a class with a property which is an enum

The enum is

/// 
/// All available delivery actions
/// 
public enum E         


        
10条回答
  •  醉酒成梦
    2020-12-08 02:13

    Enum fields are initialized as zero; an if you don't specify values in an enum, they start at zero (Email = 0, SharePoint=1, etc).

    Thus by default any field you do initialize yourself will be Email. It is relatively common to add None=0 for such cases, or alternatively use Nullable; i.e.

    /// 
    /// All available delivery actions
    /// 
    public enum EnumDeliveryAction
    {
        /// 
        /// Not specified
        /// 
        None,
    
        /// 
        /// Tasks with email delivery action will be emailed
        /// 
        Email,
    
        /// 
        /// Tasks with SharePoint delivery action 
       /// 
       SharePoint
    }
    

    You should also be sure to never treat your last expected value as a default; i.e.

    switch(action) {
        case EnumDeliveryAction.Email; RunEmail(); break;
        default: RunSharePoint(); break;
    }
    

    this should be:

    switch(action) {
        case EnumDeliveryAction.Email; RunEmail(); break;
        case EnumDeliveryAction.SharePoint; RunSharePoint(); break;
        default: throw new InvalidOperationException(
              "Unexpected action: " + action);
    }
    

提交回复
热议问题