【问题标题】:Create new enum from existing enum从现有枚举创建新枚举
【发布时间】:2015-12-17 15:37:24
【问题描述】:

我有一个现有的枚举

public enum BalanceType // existing enum
{
    Available,
    Phone,
    Commissary,
    Account,
    Reserve,
    Encumber,
    Debt,
    Held,
}

现在我想从中创建一个新的枚举。新的只包含两个字段。

 public class IvrBalanceInfo
{
    public decimal Amount { get; set; }
    public IvrBalanceType Type { get; set; }
    public IvrBalanceInfo(BalanceInfo info, BalanceType type)
    {
        Amount = info.Amount;
        //How to create the enum IvrBalanceType?
    }

    public enum IvrBalanceType // new enum
    {
        Available,
        Phone,
    }
}

我的问题是如何快速映射它?我的意思是将旧的转换为新的。旧的来自第三方。元素太多了。我只需要两个。

【问题讨论】:

  • 有什么问题?
  • 什么意思?您不能创建 枚举(除了使用反射发射生成程序集等非常丑陋的事情)。但更重要的是,你不应该做这样的事情。你到底想做什么?
  • 您是在问如何将一个enum 映射到另一个?
  • 嗯,你的意思是“我怎样才能从BalanceType 转换成IvrBalanceType”?
  • 是的,我想转换它。 @Albireo

标签: c# enums


【解决方案1】:
public class IvrBalanceInfo
{
   public decimal Amount { get; set; }
   public IvrBalanceType Type { get; set; }
   public IvrBalanceInfo(BalanceInfo info, BalanceType type)
   {
      Amount = info.Amount;
      if (type == BalanceType.Available)
         Type = IvrBalanceType.Available;
      else if(type == BalanceType.Phone)
         Type = IvrBalanceType.Phone

      // here you have to handle the other values and set the default
      // values for the Type Property or it will take the default value
      // if you not set it
   }

   public enum IvrBalanceType // new enum
   {
       Available,
       Phone,
   }
}

另一种解决方案的问题是,如果type参数的值不是BalanceType.Available、BalanceType.Phone中的值之一,它会抛出异常

【讨论】:

    【解决方案2】:

    您可以尝试以下操作:

    public class IvrBalanceInfo
    {
        public decimal Amount { get; set; }
        public IvrBalanceType Type { get; set; }
        public IvrBalanceInfo(BalanceInfo info, BalanceType type)
        {
            Amount = info.Amount;
            Type = (IvrBalanceType)(int)type;
        }
    
        public enum IvrBalanceType // new enum
        {
            Available,
            Phone,
        }
    }
    

    我认为您应该检查值或为其他值获取一些默认值。

    只是确保它可以编译,没有时间检查它是如何工作的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 2019-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多