VB.NET:动态获取常量值

标签 vb.net constants dynamic-programming generic-collections

如果有以下常量定义:

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/

相关文章:

c++ - 我应该制作所有不应该改变常量的东西吗?

algorithm - 求和为 n 的最少完全平方数

python - 如何找到将项目移动到堆栈中某个位置的最小移动次数?

vb.net - 在 VB.NET 中将单个字节 append 到字节数组

c++ - 从 const 类继承

c++ - 如何判断我使用的库、dll 和函数是否是 C++ Native

objective-c - "sending ' 常量 NSString * ' to parameter of type ' NSString * ' discards qualifiers"警告

java - 给定整数数组找到所有最长的递增子序列 - 动态规划

vb.net - 未使用的局部变量 (Visual Studio 2012)

SQL查询将1列划分为3列