I need a NOT operation on Enumeration in VB.NET (.NET 2), is 开发者_运维问答it possible?
<DefaultValue(0)> _
Public Enum Orientation
Descending = -1
Undefined = 0
Ascending = 1
End Enum
by ex define a Not operation in order to do
myObj1.Orientation = Not myObj2.Orientation
Rules:
Desceding > Ascending,
Ascending > Desceding,
Undefined > Undefined
There is no general way to do this because enumerations are an integral type and Not
on integral types does a bitwise operation which is not what you want here. However, in your case you can simply write a method that inverts the orientation:
Module OrientationExtensions
<Extension()>
Public Function Invert(ByVal orientation As Orientation) As Orientation
Return -1 * orientation
End Function
End Module
Usage:
Dim orientation As Orientation
orientation = Module1.Orientation.Ascending
orientation = orientation.Invert()
In general you'll need to code up a specific method as only you know what's the inverse of each of your enumeration values is.
There might be easier approaches for simple enumerations, but if there's a complicated relationship between the values making it explicit is the only way to go.
(You'll have to forgive the C# style pseudo code.)
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;
}
You can create an extension method:
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
Then you can use it like this:
Dim orientation As Orientation = Orientation.Ascending
Dim inverseOrientation As Orientation = orientation.Invert
精彩评论