【问题标题】:Reference Variable names as strings以字符串形式引用变量名
【发布时间】:2016-07-12 02:28:58
【问题描述】:

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

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

例如编辑

【问题讨论】:

  • 不清楚你的意思。您能否提供一个伪代码示例来演示您要实现的目标?
  • 您可以将它们放入字典中。但是你的问题听起来很奇怪。
  • 很难想象,API 使用名称而不是值...闻起来像 XY 问题
  • @Plutonix - API 有一个调用“GetField(program_reference,field_Name_As_String,Output_Buffer,Max_Size)。我可能需要与单个调用相关的任意数量的字段(它有近 100 个可能的字段名称)

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


【解决方案1】:

你需要通过Reflection找到公共字段。

有一个从此源代码编译的示例 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 

【讨论】:

    【解决方案2】:

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

    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
    

    在你的外部代码中的其他地方

    模块测试模块

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

    结束模块

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 2021-02-25
      • 2017-10-11
      • 1970-01-01
      • 2017-06-21
      相关资源
      最近更新 更多