具有多个值的枚举

时间:2018-08-28 06:52:31

标签: c# enums

在我的模型中,我有此代码

public enum StockStatus
{       
    Origin= 1,

    [Display(Name = "In Transit")]
    InTransit = 5,
    [Display(Name = "Port Louis")]
    PortLouis = 6,
    Yard = 7,
    Requested = 8
}

我需要能够为Origin提供多个类似这样的值

public enum StockStatus
{       
    Origin= 1,2,3,4,        

    [Display(Name = "In Transit")]
    InTransit = 5,
    [Display(Name = "Port Louis")]
    PortLouis = 6,
    Yard = 7,
    Requested = 8
}

我知道这还不行,但是我需要能够通过这种方式完成

5 个答案:

答案 0 :(得分:4)

您需要将枚举作为Flags且值必须按位唯一(2的幂)。

[Flags]
public enum MyEnum
{

    Origin= no1 | no2 | no3 | no4,

    no1 = 1,
    no2 = 1 << 1,
    no3 = 1 << 2,
    no4 = 1 << 3,

    [Display(Name = "In Transit")]
    InTransit = 1 << 4,
    [Display(Name = "Port Louis")]
    PortLouis = 1 << 5,
    Yard = 1 << 6,
    Requested = 1 << 7
}

答案 1 :(得分:0)

您将必须执行以下操作:

class Status
{
    static void Main(string[] args)
    {
        int code = 1;
        string name;
        Dictionary<int, string> StatusMap = new Dictionary<int, string>
        {
            { 1, "ORIGIN" },
            { 2, "ORIGIN" },
            { 3, "ORIGIN" },
            { 4, "IN TRANSIT" }
        };

   if (!StatusMap.TryGetValue(code, out name))
   {
       Console.WriteLine(name);
       // Error handling here
   }
  }
}

// or a method like this
public static string GetStatus(int code)
{
    string name;
    if (!StatusMap.TryGetValue(code, out name)
    {
        // Error handling here
    }
    return name;
}

答案 2 :(得分:0)

枚举值不能用逗号分隔。

您可以执行以下操作:

public class StockStatus
{       
    public List<int> Origin= new List<int>(){1,2,3,4};

    [Display(Name = "In Transit")]
    public List<int> InTransit = new List<int>(){ 5};
    [Display(Name = "Port Louis")]
    public List<int> PortLouis = new List<int>(){ 6};
    public List<int> Yard = new List<int>(){ 7};
    public List<int> Requested = new List<int>(){ 8};
}

这样,您将能够为Origin设置多个值

答案 3 :(得分:0)

这是不可能的,因为跟随将是模糊的。

StockStatus aStatus = StockStatus.Origin;

如果我是我,我将定义Origin和OriginMax。

Origin= 1,
OriginMax= 4,

用法:

1. StockStatus aStatus = StockStatus.Origin;
2. if (aStatus >= StockStatus.Origin && aStatus <= StockStatus.OriginMax)

答案 4 :(得分:0)

枚举的[Flags]属性使您可以立即为枚举分配多个值。您可以通过按位操作来做到这一点

[Flags]
public enum StockStatus
{
    Origin = 0x0 | 0x1 | 0x2,

    [Display(Name = "In Transit")]
    InTransit = 0x4,
    [Display(Name = "Port Louis")]
    PortLouis = 0x8,
    Yard = 0x10,
    Requested = 0x20
}