Sultanen
Sultanen

Reputation: 3412

How can i do this propertycall in a better way?

Okey, here is my problem, im calling a bunch of different propertys named K0 to K6, im using a string to check which one i need to access, this is damn messy, how can i do it in a more clean way? Im convinced that strings are not the way to go so please give me a comment to get in the right direction.

Dim tempAntDec As Integer

Select Case wd.MClass 
                    Case "K0" 
                        tempAntDec = wd.allMeasUnc.K0.antDec 
                    Case "K1" 
                        tempAntDec = wd.allMeasUnc.K1.antDec 
                    Case "K2" 
                        tempAntDec = wd.allMeasUnc.K2.antDec 
                    Case "K3" 
                        tempAntDec = wd.allMeasUnc.K3.antDec 
                    Case "K4" 
                        tempAntDec = wd.allMeasUnc.K4.antDec 
                    Case "K4-5" 
                        tempAntDec = wd.allMeasUnc.K4_5.antDec 
                    Case "K5" 
                        tempAntDec = wd.allMeasUnc.K5.antDec 
                    Case "K5-6" 
                        tempAntDec = wd.allMeasUnc.K5_6.antDec 
                    Case "K6" 
                        tempAntDec = wd.allMeasUnc.K6.antDec 
                End Select  

I would like to call this in some other way like, this.. or dont know but i feel like there is a better way to handle this?

tempAntDec = wd.allMeasUnc.KValue.antDec

Upvotes: 0

Views: 84

Answers (1)

EverPresent
EverPresent

Reputation: 1970

You might try the VB.NET CallByName Function.

If that doesn't work then give some simple reflection a try. Here is a link to a simple reflection tutorial. It's in C# but should be fairly easy to convert to VB.NET. Here's the untested code for doing it using reflection:

' Get the K-object reflectively.
Dim mytype As Type = wd.allMeasUnc.GetType()
Dim prop as PropertyInfo = mytype.GetProperty(wd.MClass) ' From the System.Reflection namespace
Dim Kobject as Object = prop.GetValue(wd.allMeasUnc, Nothing)

' Get the antDec property of the K-object reflectively.
mytype = Kobject.GetType()
prop = mytype.GetProperty("antDec")
tempAntDec = prop.GetValue(Kobject, Nothing)

Depending on your compiler settings you may need to use DirectCast to convert the last line into an integer (because GetValue returns it as a plain Object). Something like "tempAntDec = DirectCast(prop.GetValue(Kobject, Nothing), Integer)" would probably work if needed.

Upvotes: 1

Related Questions