引用变量名称为字符串

时间:2016-03-24 13:19:18

标签: vb.net variables dll reflection class-library

我试图将变量的名称作为字符串引用。我有一个全局变量列表

Public gvHeight As String = Blank
Public gvWeight As String = Blank
Public gvAge As String = Blank

我需要引用外部API调用的变量名称。我试图避免每个变量的特定代码,而是允许我添加一个新变量和一切正确引用。我已经有了其余的代码来处理名称作为字符串。

示例:

public Height as string
public weight as string
public age as string

[elsewhere in code]
for each var as string in {public variables}
   CallToAPI(var.name) 'needs to send "height" "weight" or "age" but there are a lot so hardcoding is not a good solution

编辑了例如

2 个答案:

答案 0 :(得分:1)

您需要通过反射找到公共字段。

从这个源代码编译一个示例dll:

Public Class Class1

    Public Field1 As String = "value 1"
    Public Field2 As String = "value 2"
    Public Field3 As Integer

End Class

然后你可以这样做:

' The library path.
Dim libpath As String = "...\ClassLibrary1.dll"

' The assembly.
Dim ass As Assembly = Assembly.LoadFile(libpath)

' The Class1 type. (full namespace is required)
Dim t As Type = ass.GetType("ClassLibrary1.Class1", throwOnError:=True)

' The public String fields in Class1.
Dim strFields As FieldInfo() =
    (From f As FieldInfo In t.GetFields(BindingFlags.Instance Or BindingFlags.Public)
     Where f.FieldType Is GetType(String)
    ).ToArray

' A simple iteration over the fields to print their names.
For Each field As FieldInfo In strFields
    Console.WriteLine(field.Name)
Next strField 

答案 1 :(得分:0)

如果所有变量属于同一类型(此处为字符串),则可以使用Dictionary ...

Public MyModule
  Private myVars As Dictionary(Of String, String)

  Public Function CallToAPI(VarName As String) As String
      If myVars.ContainsKey(VarName) Then
          Return myVars(VarName)
      End If
      Return ""
  End Function
End Module

外部代码中的其他地方

模块TestModule

Public Sub Test()
    Dim myVar = MyModule.CallToAPI("test")

End Sub

结束模块

现在,如果你的变量不一样,那么你必须使用反射......这就是乐趣开始的地方......