February 28, 2009

列出列舉(Enumeration)內成員名稱及列舉值的方法

一列舉Family如下
Protected Enum Family As Integer
  Grandpa = 0
  Grandma = 1
  Father = 2
  Mother = 3
  Brother = 4
  Sister = 5
End Enum

以下示範如何列出此列舉內的列舉名稱及值
'列出列舉成員名稱
Me.Response.Write("列出列舉成員名稱<br />")
For Each str As String In [Enum].GetNames(GetType(Family))
  Me.Response.Write(str)
  Me.Response.Write("<br />")
Next

Me.Response.Write("<p></p>")

'列出列舉值
Me.Response.Write("列出列舉值<br />")
For Each value As Integer In [Enum].GetValues(GetType(Family))
  Me.Response.Write(value.ToString())
  Me.Response.Write("<br />")
Next

Me.Response.Write("<p></p>")

'經由列舉值取得列舉成員名稱
Me.Response.Write("經由列舉值取得列舉成員名稱<br />")
For Each value As Integer In [Enum].GetValues(GetType(Family))
  Me.Response.Write("值:" & value.ToString() & " 名稱:" & [Enum].GetName(GetType(Family), value))
  Me.Response.Write("<br />")
Next

顯示結果如下:

No comments: