在VB.NET中反转枚举

时间:2010-09-10 09:21:42

标签: .net vb.net .net-2.0

我需要对VB.NET(.NET 2)中的Enumeration进行NOT操作,是否可能?

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

通过ex定义 Not 操作来执行

myObj1.Orientation = Not myObj2.Orientation

规则:

Desceding > Ascending, 
Ascending > Desceding, 
Undefined > Undefined

3 个答案:

答案 0 :(得分:5)

没有一般的方法可以做到这一点,因为枚举是一个整数类型,而整数类型的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()

答案 1 :(得分:0)

通常,您需要对特定方法进行编码,因为只有您知道每个枚举值的倒数是什么。

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

(你必须原谅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;
}

答案 2 :(得分:0)

您可以创建扩展方法:

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