C#中的枚举布尔值

时间:2016-10-20 13:48:49

标签: c# enums

我有这个方法

public enum Values
{
    True= true,
    False=false
};
public static string GetValues(bool values)
{
    string status = "";
    switch (values)
    {
        case(bool)UIHelper.Values.False:

    }
}

我想将enum作为boolean。它说:

  

值无法作为bool转换。

我该怎么做才能拥有它boolean

4 个答案:

答案 0 :(得分:4)

当然,你可以映射到0(Service)和1(Serial),但为什么要映射到那个?为什么不从一开始就使用bool?

public static class UnlPointValues
{
    public const bool Serial = true;
    public const bool Service = false;
}

public static string GetUnloadingPointValues(bool values)
{
    string status = "";
    switch (values)
    {
        case UIHelper.UnlPointValues.Serial:

    }
}

答案 1 :(得分:0)

0使用false1使用true代替Convert.ToBoolean

  

如果值不为零,则为true;否则,错误。

public enum UnlPointValues
{
    Serial = 1,  //true
    Service = 0  //false
};

public static string GetUnloadingPointValues(bool values)
{
    string status = "";
    switch (values)
    {
        case (Convert.ToBoolean((int)UIHelper.UnlPointValues.Serial)):
        break;
        case (Convert.ToBoolean((int)UIHelper.UnlPointValues.Service)):
        break;
    }
}

答案 2 :(得分:0)

如果你必须坚持enum,你可以实施扩展方法

  public enum Values {
    True,
    False,
    // and, probably, some other options
  };

  public static class ValuesExtensions {
    public static bool ToBoolean(this Values value) {
      // which options should be treated as "true" ones
      return value == Values.False;
    }
  }

...

// you, probably want to check if UIHelper.Values is the same as values 
if (values == UIHelper.Values.ToBoolean()) {
  ...
}

答案 3 :(得分:0)

我在这里看不到你需要enum

public static string GetUnloadingPointValues(bool isSerial)
{
    return isSerial ? "Serial" : "Service";
}

或者您要映射的string值。

相关问题