获得一个采用的反射式的静态字段值字段、静态、反射式

2023-09-02 10:51:22 作者:槍口走火

我有一组静态枚举类,我用持有有意义的变量名来重新接受我的输入文件present毫无意义了code值。这里有一个示例。

I've got a set of static "enumeration" classes that I'm using to hold meaningful variable names to represent meaningless code values I receive on an input file. Here's an example of one.

Public Class ReasonCodeValue
    Private Sub New()
    End Sub
    Public Shared ReadOnly ServiceNotCovered As String = "SNCV"
    Public Shared ReadOnly MemberNotEligible As String = "MNEL"
End Class

欲写将接受这些静态类中的一个的类型以及一个字符串值,并确定该值是否是静态字段值之一的方法。我知道如何获得特定对象的实例字段,我知道如何让静态字段特定类型的列表;我无法弄清楚是如何得到的静态字段值,而一个实例。以下是我有这么远。

I want to write a method that will accept the type of one of these static classes and a string value and determine whether the value is one of the static field values. I know how to get the instance fields for a specific object, and I know how to get a list of static fields for a specific type; what I can't figure out is how to get the static field values without an instance. Here's what I've got so far.

Public Function IsValidValue(ByVal type As Type, ByVal value As String) As Boolean
    Dim fields = type.GetFields(BindingFlags.Public Or BindingFlags.Static)
    For Each field As FieldInfo In fields
        DoSomething()
    Next
End Function

我认为我可以让枚举类的非静态的,这样我可以创建一个实例传递给 FieldInfo.GetValue 在我的验证方法。我宁愿让我的阶级是,如果我能方式。

I supposed I could make the enumeration classes non-static just so I can create an instance to pass to FieldInfo.GetValue inside my validation method. I'd rather keep my class the way it is if I can.

我看到一个名为方法 GetRawConstantValue 。它看起来很危险。这会否给我我想要的?任何其他的想法?

I see a method called GetRawConstantValue. It looks dangerous. Will that give me what I'm looking for? Any other ideas?

推荐答案

呼叫

field.GetValue(Nothing)

,它会被罚款。你不需要为静态成员的实例。

and it'll be fine. You don't need an instance for static members.

我不的认为的 GetRawConstantValue 是你想要的 - 我会坚持到code以上

I don't think GetRawConstantValue is what you want - I'd stick to the code above.