我怎样才能以更好的方式打电话?

时间:2012-02-03 01:30:14

标签: vb.net properties

哎呀,这是我的问题,我叫一堆名为K0到K6的不同属性,我用一个字符串来检查我需要访问哪一个,这是该死的,我怎么能以更干净的方式做到这一点?我确信字符串不是要走的路,所以请给我一个评论,以便朝着正确的方向前进。

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  

我想用其他方式来称呼这个......或者不知道,但我觉得有更好的办法处理这个问题?

tempAntDec = wd.allMeasUnc.KValue.antDec

1 个答案:

答案 0 :(得分:1)

您可以尝试使用VB.NET CallByName Function

如果这不起作用那么尝试一些简单的反思。这是一个简单reflection tutorial的链接。它在C#中,但应该很容易转换为VB.NET。以下是使用反射执行此操作的未经测试的代码:

' 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)

根据您的编译器设置,您可能需要使用DirectCast将最后一行转换为整数(因为GetValue将其作为普通对象返回)。像“tempAntDec = DirectCast(prop.GetValue(Kobject,Nothing),Integer)”这样的东西可能会在需要的时候起作用。