Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

.net - Getting static field values of a type using reflection

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Call

field.GetValue(Nothing)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...