如果有以下常量定义:
Protected Const Xsl As String = "Configuration.Xsl"
Protected Const Form As String = "Settings.Form"
Protected Const Ascx As String = "Implementation.Ascx"
...
为了填充字典,我使用这个常量作为键:
MyDictionary.Add(Converter.Xsl, "Item 1")
MyDictionary.Add(Converter.Form, "Item 2")
MyDictionary.Add(Converter.Ascx, "Item 3")
...
现在我运行一个 XML 文件循环并提取根节点的名称:
Dim document As New XmlDocument
document.Load(File.FullName)
Dim rootName As String = document.DocumentElement.Name
根名称与常量名称匹配。要从字典中获取项目的值,我可以使用如下内容:
Select Case rootName.ToUpper
Case "Xsl".ToUpper
DictionaryValue = MyDictionary(Class.Xsl)
Case "Form".ToUpper
DictionaryValue = MyDictionary(Class.Form)
Case "Ascx".ToUpper
DictionaryValue = MyDictionary(Class.Ascx)
...
Case Else
End Select
如果添加或删除常量,我还必须更改选择。还有其他方法可以获取常量的值吗?类似的东西
DictionaryValue = MyDictionary(SomeFunctionToGetConstantValue(rootName))
感谢您的回复。
最佳答案
试试这个:
For Each sKey As String In MyDictionary.Keys
If rootName.Equals(sKey, StringComparison.CurrentCultureIgnoreCase) Then
DictionaryValue = MyDictionary(sKey)
Exit For
End If
Next
至少它会减少选择案例中的编码量。
关于VB.NET:动态获取常量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16031453/