使用变量name作为字符串,使用循环设置变量 [英] Set variable with a loop using the variables name as a string

查看:108
本文介绍了使用变量name作为字符串,使用循环设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好。我的应用程序需要以不同的形式和子设置多次设置和检索变量。我没有多次编写代码,而是希望使用循环来循环变量并相应地设置它们。这就是我到目前为止所拥有的。我坚持根据其名称设置变量(见下文)。

Hi All. My application requires variables to be set and retrieved multiple times in different forms and subs. Instead of writing the code multiple times i was hoping to use a loop to loop through the variables and set them accordingly. This is what i have so far. I'm stuck with setting the variable based on its name (See below).

Dim VariableA As Integer
Dim VariableB As String
Dim VariableC As Boolean
Dim VariableD As Double
Dim VariableNames(3) As String
Dim VariableValues(3) As String

Private Sub SetVariables()

    VariableNames = {"VariableA", "VariableB", "VariableC", "VariableD"}
    VariableValues = {"1", "Hello", "True", "2.234"}

    For i As Integer = 0 To VariableNames.Length - 1
        SetValue(VariableNames(i), VariableValues(i))
    Next

End Sub

Private Sub SetValue(ByVal Name As String, ByVal value As Object)

    'what do i add here

End Sub





我尝试了什么:



我试过了一个字典,但它似乎只引用了未设置变量的值



What I have tried:

I've tried a dictionary but it only seems to reference the value not set the variable

推荐答案

是的,你不能这样做。



在.NET中确实没有全局变量这样的东西。你最接近的是静态(在VB.NET中共享)类或模块。我建议去静态类路线。



这个问题就是你看起来好像在试图实现一个属性包。这是键/值对的集合,其中键始终是字符串,值可以是任何类型。基本上,这个:

Yeah, you can't do that.

There is really no such thing as a "global" variable in .NET. The closest you're going to get is a static (Shared in VB.NET) class or Module. I would recommend going the static class route.

The problem with this is that it looks like you're trying to implement a "property bag". That is a collection of key/value pairs where the key is always a string and the value can be any type. Basically, this:
Dim _bag As Dictionary(Of String, Object)



这样做有些问题。一个相当讨厌的是你放松了类型安全。您可以将变量(实际上只是字典中的一个键)设置为您想要的任何类型的值。所以,如果一个变量需要是一个整数,但你不小心写了一个字符串,那么在读取整数的代码爆炸并引发异常之前,没有什么可以说你做错了。



然后有预期的值,拳击/拆箱,......



如果你有一个固定的变量集,如果你真的需要它们是全局的,那么将它们公开为共享类中的共享属性。您保留了类型安全性,性能以及更容易支持(读取:可调试)的代码。



但是,如果您使用的是全局变量,那么这是提示您可能需要重新考虑如何设计代码。


The are a few problem with doing this. One rather nasty one is that you loose type safety. You can set a "variable", really just a key in the dictionary, to any type of value you want. So, if a variable needs to be an integer, but you accidentally write a string to it, there's nothing that will say what you did was wrong until the code reading the "integer" blows up and throws an exception.

Then there's casting values to what's expected, boxing/unboxing, ...

It would be better if you had a fixed set of variables, and if you REALLY needed them to be "global" expose them as Shared properties in a Shared class. You retain type safety, performance, and more easily supported (read: debuggable) code.

But, if you're using "global" variables at all, this is a hint that you probably have to rethink how you're designing your code.


我使用了反射



I used a reflection

Dim Flags As BindingFlags = BindingFlags.GetField Or BindingFlags.Instance Or BindingFlags.Public
Dim fVar As System.Reflection.FieldInfo = Me.GetType.GetField(ObjectName, Flags)

If TypeOf SettingsTabControl.TabPages(TabPageIndex).Controls(CtrlName) Is TextBox Then
    ctrlValue = SettingsTabControl.TabPages(TabPageIndex).Controls(CtrlName).Text
ElseIf TypeOf SettingsTabControl.TabPages(TabPageIndex).Controls(CtrlName) Is CheckBox Then
    ctrlValue = CType(SettingsTabControl.TabPages(TabPageIndex).Controls(CtrlName), CheckBox).Checked
ElseIf TypeOf SettingsTabControl.TabPages(TabPageIndex).Controls(CtrlName) Is RadioButton Then
    ctrlValue = CType(SettingsTabControl.TabPages(TabPageIndex).Controls(CtrlName), RadioButton).Checked
End If

fVar.SetValue(Me, ctrlValue)


谢谢戴夫。我将研究一下铸造方法



我认为简化的例子会更有益。这是我的确切代码。



下面的imedialty部分是菜单类。这个位按预期工作

Thanks Dave. I'll look into the casting method

I thought a simplified example would be more beneficial. here is my exact code.

The section imedialty below are the menu classes. This bit works as expected
Public Class MenuItem

    Public Name As String
    Public Type As TypeEnum

    Enum TypeEnum
        CheckBox
        ComboBox
        TextBox
    End Enum     

    Public Sub New()
    End Sub

End Class

Public Class Menu

    Public MenuItems() As MenuItem
    Public Name As String
    Public LinkedVariable as Object

    Public Sub New()
    End Sub

    Public Sub AddMenuItem(ByVal ItemName As String, _
                           ByVal ItemType As MenuItem.TypeEnum, _
                           ByVal ItemLinkedVariable as Object)   

        If MenuItems Is Nothing Then
            ReDim MenuItems(0)
        Else
            ReDim Preserve MenuItems(MenuItems.Length)
        End If
        MenuItems(MenuItems.Length - 1) = New MenuItem
        MenuItems(MenuItems.Length - 1).Name = ItemName
        MenuItems(MenuItems.Length - 1).Type = ItemType
        MenuItems(MenuItems.Length - 1).LinkedVariable = ItemLinkedVariable 
    End Sub

End Class





在主表单类中构建菜单。这个位按预期工作





Build the menus in the main form class. This bit works as expected

Public Class Form1
    Public Settings As New SettingsForm
    Public Sub CreateMenu()

        Settings.AddMenu("Menu1")

        Settings.Menus(0).AddMenuItem("CheckBoxA", MenuItem.TypeEnum.CheckBox, VariableA)
        Settings.Menus(0).AddMenuItem("TextBoxB", MenuItem.TypeEnum.TextBox, VariableB)
        Settings.Menus(0).AddMenuItem("TextBoxC", MenuItem.TypeEnum.TextBox, VariableC) 

        Settings.AddMenu("Menu2")

        Settings.Menus(1).AddMenuItem("CheckBoxD", MenuItem.TypeEnum.CheckBox, VariableD)
        Settings.Menus(1).AddMenuItem("TextBoxE", MenuItem.TypeEnum.TextBox, VariableE)

        'etc......      

        Settings.Build()

        Settings.Show()

    End Sub
End Class


Public Class SettingsForm
    Public Menus() As Menu

    Public VariableA As Boolean
    Public VariableB As String
    Public VariableC As String
    Public VariableD As Boolean
    Public VariableE As String

    Public Sub New()

        InitializeComponent()

    End Sub

    Public Sub Build()

        SettingsTabControl.TabPages.Clear()

        If Menus IsNot Nothing Then
            For i As Integer = 0 To Menus.Length - 1

                SettingsTabControl.TabPages.Add(Menus(i).Name)
                SettingsTabControl.TabPages(i).Name = Menus(i).Name & "TabPage"
                SettingsTabControl.TabPages(i).Text = Menus(i).Name

                AddSettingsItems(Menus(i), i)

            Next
        End If

    End Sub

    Public Sub AddSettingsItems(ByVal SelectedMenu As Menu, ByVal TabPageIndex As Integer)
        Dim y As Integer = 50
        Dim yinc As Integer = 25

        If SelectedMenu IsNot Nothing Then
            If SelectedMenu.MenuItems IsNot Nothing Then

                For i As Integer = 0 To SelectedMenu.MenuItems.Length - 1

                    Dim formObj As Object

                    'Specific Settings
                    Select Case SelectedMenu.MenuItems(i).Type
                        Case MenuItem.TypeEnum.CheckBox
                            formObj = New CheckBox
                        Case MenuItem.TypeEnum.ComboBox
                            formObj = New ComboBox                            
                        Case MenuItem.TypeEnum.TextBox
                            formObj = New TextBox
                            formObj.TextAlign = HorizontalAlignment.Right
                            formObj.BorderStyle = BorderStyle.FixedSingle
                    End Select

                    formObj.Name = SelectedMenu.MenuItems(i).Name
                    formObj.Location = New Point(25, y)
                    SettingsTabControl.TabPages(TabPageIndex).Controls.Add(formObj)

                    y = y + yinc
                Next
            End If
        End If
    End Sub
End Class





这是我坚持的一点,我希望能够从添加到SettingsTabControl的控件中设置变量A,B,C,D,E。但是我无法弄清楚如何将变量链接到每个MenuItem中的LinkedVariable对象。这就是我所拥有但它不起作用





This is the bit i am stuck on i want to be able to set the Variables A,B,C,D,E from the controls that were added to the SettingsTabControl. However i can't work out how to link the Variables to the LinkedVariable objects in each MenuItem. This is what i have but it doesn't work

Private Sub SettingsFromOkButton_Click(sender As Object, e As EventArgs) Handles OkButton.Click

    For m As Integer = 0 To Menus.Length - 1
        For i As Integer = 0 To Menus(m).MenuItems.Length

            Dim currentcontrol As Object = SettingsTabControl.TabPages(m).Controls(Menus(m).MenuItems(i).Name)

            Select Case Menus(m).MenuItems(i).Type
                Case MenuItem.TypeEnum.CheckBox
                    If currentcontrol.CheckedState = True Then
                        Menus(m).MenuItems(i).LinkedVariable = True
                    Else
                        Menus(m).MenuItems(i).LinkedVariable = False
                    End If
                Case MenuItem.TypeEnum.ComboBox


                Case MenuItem.TypeEnum.TextBox
                    Menus(m).MenuItems(i).LinkedVariable = currentcontrol.Text
            End Select

        Next
    Next

    MsgBox(VariableA & vbCrLf _
           VariableB & vbCrLf _
           VariableC & vbCrLf _
           VariableD & vbCrLf _
           VariableE & vbCrLf)

End Sub


这篇关于使用变量name作为字符串,使用循环设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆