我正在尝试使用字符串变量的值来成为我的新变量的名称。例如,见下面的代码。我这样做的原因是我有一个文本文件,其中包含我需要为其创建对象的变量的名称。也许有另一种方法可以做到这一点?
Dim mystring As String
mystring = "Variablename"
'dim "Variablename" as object
答案 0 :(得分:0)
如何使用收藏品?集合中项目的键将是您的变量名称,集合中项目的值是您的变量。
答案 1 :(得分:0)
以下是使用自定义属性创建类的示例。如果你想要走这条路,这应该可以帮到你:
' Note: There is no root namespace in the project properties
Imports System.CodeDom.Compiler
Imports System.Reflection
Namespace Foo
Module Module1
Sub Main()
Dim instance = createInstance({"Prap", "Prep", "Prip", "Prop", "Prup"})
instance.Prap = "Prappy"
Console.WriteLine(instance.Prap)
End Sub
Private Function createInstance(propertyNames As IEnumerable(Of String)) As Object
Dim codeProvider As New VBCodeProvider()
Dim codeCompiler As ICodeCompiler = codeProvider.CreateCompiler()
Dim compilerParameters As New CompilerParameters()
compilerParameters.CompilerOptions = "/target:library"
Dim code =
"NameSpace Foo" & Environment.NewLine &
" Partial Public Class Bar" & Environment.NewLine
For Each name In propertyNames
code &=
String.Format(" Public Property {0} As String", name) & Environment.NewLine
Next
code &= " End Class" & Environment.NewLine &
"End Namespace"
Console.WriteLine("Code to compile:")
Console.WriteLine(code)
Dim result = codeCompiler.CompileAssemblyFromSource(compilerParameters, code)
If result.Errors.HasErrors Then
Console.WriteLine(result.Errors.OfType(Of CompilerError).Aggregate(Of String)("Errors:", Function(e1, e2) e1 & ", " & e2.ErrorText))
Return Nothing
Else
Console.WriteLine("Success")
Dim type As Type = result.CompiledAssembly.GetType("Foo.Bar")
Dim instance = Activator.CreateInstance(type)
Return instance
End If
End Function
End Module
End Namespace
输出:
编译代码:
NameSpace Foo
部分公共类酒吧
公共财产包裹为字符串
公共财产准备字符串
公共财产Prip As String
公共财产支柱字符串
公共财产Prup As String
结束班
结束命名空间
成功
Prappy
现在,您还可以构建具有不同于String的属性类型的类,该类是硬编码的。只需将它作为一个单独的数组包含在参数中,或者你可以使用元组或字典等。祝你好运!