How to obtain a list of constants in a class and their values

前端 未结 2 776
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-16 03:46

I have a class in VB with some constants that represent the string name of my security roles. I need to be able to call a function to return to me a string array(or collect

相关标签:
2条回答
  • 2021-01-16 04:49

    Ok, here's how it is done. I didn't do this on my own though, http://weblogs.asp.net/whaggard/archive/2003/02/20/2708.aspx had the answer, I just ran it through a C# to VB.Net converter.

    Function GetStringsFromClassConstants(ByVal type As System.Type) As String()
        Dim constants As New ArrayList()
        Dim fieldInfos As FieldInfo() = type.GetFields(BindingFlags.[Public] Or _ 
            BindingFlags.[Static] Or BindingFlags.FlattenHierarchy)
    
        For Each fi As FieldInfo In fieldInfos
            If fi.IsLiteral AndAlso Not fi.IsInitOnly Then
                constants.Add(fi)
            End If
        Next
    
        Dim ConstantsStringArray as New System.Collections.Specialized.StringCollection
    
        For Each fi as FieldInfo in _ 
            DirectCast(constants.ToArray(GetType(FieldInfo)), FieldInfo())
            ConstantsStringArray.Add(fi.GetValue(Nothing))
        Next
    
        Dim retVal(ConstantsStringArray.Count - 1) as String
        ConstantsStringArray.CopyTo(retval,0)
        Return retval    
    End Function
    
    0 讨论(0)
  • 2021-01-16 04:50

    You can build an object that is nearly identical to a string enum in VB.Net. See my previous post on the topic here:

    Getting static field values of a type using reflection

    0 讨论(0)
提交回复
热议问题