如何获取类中的常量及其值的列表 [英] How to obtain a list of constants in a class and their values

查看:413
本文介绍了如何获取类中的常量及其值的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在VB中有一个带有一些常量的类,这些常量代表我的安全角色的字符串名称。我需要能够调用一个函数以向我返回这些常量中每个常量的值的字符串数组(或集合,或任何形式)。我将使用它来确保我的数据库角色表具有与应用程序中编码相同的角色。

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 collection, or whatever) of the values of each of these constants. I will be using it to make sure that my databases Roles table has the same roles as coded into the application.

Public Class Roles
    Public Const Administrator = "Administrator"
    Public Const BasicUser = "Basic User"
    Public Const PowerUser = "Power User"
End Class

我想运行一个函数,即ClassConstantsToStringArray(gettype(Roles)),该函数将返回给我管理员,基本用户 ,超级用户

I'm looking to run a function, i.e. ClassConstantsToStringArray(gettype(Roles)) that will return to me "Administrator","Basic User","Power User"

我知道反思是必经之路,我只是对使用它还不够了解。我在网上找到了一个函数,该函数可以将FieldInfo数组中的常量名称返回给我,但仍然没有足够的智能来为我工作。

I'm know reflection is the way to go, I just don't know enough about using it yet to get what I want. I found a function on the net that would return to me the constant names in a FieldInfo array but still don't have enough smarts to make that work for me.

谢谢

推荐答案

好的,这是完成的方法。不过,我不是一个人做的, http:/ /weblogs.asp.net/whaggard/archive/2003/02/20/2708.aspx 有了答案,我只是通过C#将其运行到VB.Net转换器。

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

这篇关于如何获取类中的常量及其值的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆