代码之家  ›  专栏  ›  技术社区  ›  serhio

在中反转枚举VB.NET版

  •  0
  • serhio  · 技术社区  · 14 年前

    我需要对中的枚举执行NOT操作VB.NET版(.NET 2),是否可能?

      <DefaultValue(0)> _
      Public Enum Orientation
        Descending = -1
        Undefined = 0
        Ascending = 1
      End Enum
    

    按ex定义 为了做手术

    myObj1.Orientation = Not myObj2.Orientation
    

    规则:

    Desceding > Ascending, 
    Ascending > Desceding, 
    Undefined > Undefined
    
    3 回复  |  直到 14 年前
        1
  •  5
  •   Dirk Vollmar    14 年前

    由于枚举是整型的,因此没有通用的方法来完成此操作 Not 对整型执行按位运算,这不是您在这里想要的。但是,在您的情况下,您可以简单地编写一个反转方向的方法:

    Module OrientationExtensions
    
        <Extension()>
        Public Function Invert(ByVal orientation As Orientation) As Orientation
            Return -1 * orientation
        End Function
    
    End Module
    

    用法:

    Dim orientation As Orientation
    orientation = Module1.Orientation.Ascending
    orientation = orientation.Invert()
    
        2
  •  0
  •   ChrisF toni    14 年前

    你只需要知道在你的代码中,每一个逆的枚举值是什么。

    对于简单的枚举可能有更简单的方法,但是如果值之间存在复杂的关系,那么将其显式化是唯一的方法。

    (您必须原谅C风格的伪代码。)

    public Orientation invert(Orientation original)
    {
        Orientation result;
        switch (original)
        {
            case Orientation.Descending:
                result = Orientation.Ascending;
                break;
            case Orientation.Ascending:
                result = Orientation.Descending;
                break;
            default:
                result = original;
                break;
        }
        return result;
    }
    
        3
  •  0
  •   Martin Liversage    14 年前

    可以创建扩展方法:

    Imports System.Runtime.CompilerServices
    
    Module OrientationExtensions
    
      <Extension()>
      Public Function Invert(ByVal orientation As Orientation) As Orientation
        If orientation = Orientation.Ascending Then
          Return Orientation.Descending
        ElseIf orientation = Orientation.Descending Then
          Return Orientation.Ascending
        Else
          Return Orientation.Undefined
        End If
      End Function
    
    End Module
    

    Dim orientation As Orientation = Orientation.Ascending
    Dim inverseOrientation As Orientation = orientation.Invert