Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...