顯然我不能在 Dictionary 宣告行中使用 strName ,但我只是將它放在那里代表我正在嘗試做的事情。例如,如果用戶輸入“胡蘿卜”,我希望創建的字典命名為胡蘿卜。有沒有辦法做到這一點?
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strName As String
strName = TextBox1.Text
Dim strName As New Dictionary(Of String, String)
End Sub
End Class
uj5u.com熱心網友回復:
你不能。該名稱對于除錯很有用,實際上編譯器無論如何都不會使用該名稱 - 該名稱將保存在 pdb 檔案中,別無他處。
如果您需要按名稱跟蹤某些字典,則可以使用另一個字典,例如:
Private dictionaries As New Dictionary(Of String, Dictionary(Of String, String))()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strName = TextBox1.Text
Dim myNamedDictionary As Dictionary(Of String, String)
If dictionaries.ContainsKey(strName) Then
myNamedDictionary = dictionaries(strName)
Else
myNamedDictionary = New Dictionary(Of String, String)()
dictionaries.Add(strName, myNamedDictionary)
End If
' now you have a dictionary for the name you entered (carrot)
End Sub
檢索
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim carrotDictionary = dictionaries("carrot")
End Sub
我認為這與您將得到的一樣接近。
uj5u.com熱心網友回復:
你可以,有點。使用編譯器您可以編譯自己的代碼,但最終結果似乎無法使用,我懷疑這是您想要做的
Option Strict Off
Imports System.Reflection
Imports System.CodeDom.Compiler
Public Class Form1
Private dictionaryInstance As Object
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strName = TextBox1.Text
Dim t = GetType(Form1)
Dim ns = t.Namespace
Dim provider = New VBCodeProvider()
Dim params = New CompilerParameters()
params.GenerateInMemory = True
params.ReferencedAssemblies.Add(Assembly.GetEntryAssembly().Location)
params.OutputAssembly = "OutputAssembly"
Dim code =
$"
Imports System
Imports System.Collections.Generic
Namespace {ns}
Partial Public Class DictionaryClass
Public {strName} As New Dictionary(Of String, String)
End Class
End Namespace"
Dim results = provider.CompileAssemblyFromSource(params, {code})
Dim assy = results.CompiledAssembly
Dim o As Object = assy.CreateInstance($"{ns}.DictionaryClass")
Me.dictionaryInstance = o
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
dictionaryInstance.carrot.Add("a", "b")
End Sub
End Class
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/426194.html
標籤:VB.net
上一篇:Unix時間戳到HH-mm-ss
