VB.Net Tutorial/Data Type/Enum
Версия от 16:40, 26 мая 2010; (обсуждение)
Содержание
Assign value to Enum elements
Public Enum AccessLevel
Clerk = 10
Supervisor
Administrator = -1
End Enum
public class Test
public Shared Sub Main
Dim m_AccessLevel As AccessLevel
m_AccessLevel = AccessLevel.Supervisor
End Sub
End class
Assign value to only one Enum element
Public Enum AccessLevel
Clerk
Supervisor
Administrator
User = 0
Manager
SysAdmin
Superuser = SysAdmin
End Enum
public class Test
public Shared Sub Main
Dim m_AccessLevel As AccessLevel
m_AccessLevel = AccessLevel.Supervisor
End Sub
End class
Cast Integer to Enum value
Public Enum AccessLevel
Clerk
Supervisor
Administrator
User = 0
Manager
SysAdmin
Superuser = SysAdmin
End Enum
public class Test
public Shared Sub Main
Dim m_AccessLevel As AccessLevel
Dim integer_value As Integer = 1
m_AccessLevel = CType(integer_value, AccessLevel)
Dim access_level As AccessLevel = AccessLevel.Clerk
Console.WriteLine(access_level.ToString())
End Sub
End class
Clerk
Compare Enum element using logic operator
Public Enum workDays
Saturday
Sunday = 0
Monday
Tuesday
Wednesday
Thursday
Friday
invalid = -1
End Enum
Public Class Tester
Public Shared Sub Main
Dim MyDay As WorkDays
MyDay = WorkDays.Saturday
If MyDay < workDays.FriDay Then
Console.WriteLine("It"s the weekend.Invalid work day!")
End If
End Sub
End Class
It"s the weekend.Invalid work day!
Convert Enum to Integer
Module Module1
Enum Temperatures
A = 0
B = 32
C = 60
D = 72
E = 212
End Enum
Sub Main( )
System.Console.WriteLine("B: {0}",CInt(Temperatures.B))
System.Console.WriteLine("E: {0}", CInt(Temperatures.E))
End Sub
End Module
B: 32 E: 212
Declare Enum variable
Public Enum AccessLevel
Clerk
Supervisor
Administrator
End Enum
public class Test
public Shared Sub Main
Dim m_AccessLevel As AccessLevel
m_AccessLevel = AccessLevel.Supervisor
End Sub
End class
Define and use Enum as Integer
Option Strict On
<Flags> Public Enum MyValues As Integer
AA = 1
BB = 2
CC = 4
DD = 8
End Enum
Public Module modMain
Public Sub Main()
Dim Computer1 As MyValues = MyValues.AA Or MyValues.BB
Console.WriteLine(Computer1.ToString())
End Sub
End Module
AA, BB
Define Enum and assign value
Module Module1
Enum Temperatures
A = 0
B = 32
C = 60
D = 72
E = 212
End Enum
Sub Main( )
System.Console.WriteLine("B: {0}",Temperatures.B)
System.Console.WriteLine("E: {0}",Temperatures.E)
End Sub
End Module
B: B E: E
Enum value duplication
Public Enum AccessLevel
Level1
Level2
Level3
AliasLevel1 = Level1
AliasLevel2 = Level2
AliasLevel3 = Level3
AliasLevel4 = Level3
End Enum
public class Test
public Shared Sub Main
Dim access_level As AccessLevel = AccessLevel.Level1
Console.WriteLine(access_level.ToString())
Console.WriteLine(AccessLevel.Level1.ToString())
Console.WriteLine(AccessLevel.Level2.ToString())
Console.WriteLine(AccessLevel.Level3.ToString())
End Sub
End class
Level1 Level1 Level2 AliasLevel3