使用私人功能

时间:2010-10-30 15:59:14

标签: vb.net

您好 我使用以下代码来运行私有函数。 我的组合框中有两个值,一个和两个以及两个具有相同名称的私有函数,Private Sub One()和Private Sub Two()

我希望我的应用程序在组合框中调用用户选择的任何值的函数。 如果在组合框中选择了One,则应调用私有函数1。 谢谢 代码如下,不起作用

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim vrValue = ComboBox1.Items(1)

    Call vrValue()' In this case vrValue is Two, so Two() should be called.
End Sub
Private Sub two()
    MsgBox("Function called")
End Sub

3 个答案:

答案 0 :(得分:1)

创建子函数(唯一的区别是返回值)并将它们放在自己的类中:

Public Class RunFunctions
    Dim oMessageBox As MessageBox
    Public Function One() As String
        'oMessageBox = MessageBox
        Return "Message One"

    End Function

    Public Function Two() As String
        Return "Message Two"

    End Function
End Class

将类中的每个函数添加为组合框中的项目:

Public Class Combo_Functions
    Dim oRunFunction As RunFunctions
    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object _
           , ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        MessageBox.Show(ComboBox1.Items(ComboBox1.SelectedIndex()))

    End Sub

    Private Sub Combo_Functions_Load(ByVal sender As Object _
                                       , ByVal e As System.EventArgs) Handles Me.Load
        oRunFunction = New RunFunctions

        ComboBox1.Items.Add(oRunFunction.One())
        ComboBox1.Items.Add(oRunFunction.Two())

    End Sub
End Class

更改组合框(或使用按钮单击的代码)时,将执行正确功能的消息框。

答案 1 :(得分:0)

Dim vrValue = ComboBox1.SelectedItem.ToString()

Select vrValue
    Case "One"
        One()
    Else
        Two()
End Select

答案 2 :(得分:-1)

看起来你要做的是使用包含其名称的字符串变量动态调用特定方法。例如,组合框将包含“One”和“Two”项,如果选择了组合框中的第一项,则调用名为“One”的子,如果第二项是第二项,则调用名为“Two”的子选择。为此,您可能会发现这篇文章很有趣:

http://www.codeproject.com/KB/cs/CallMethodNameInString.aspx

文章中的代码是C#,转换为VB应该不会太难。但这里是代码的翻译版本,用于简单地调用方法而不传递或返回任何参数(注意:我没有测试过这段代码)。它只是使用反射来找到合适的方法:

Public Shared Sub InvokeStringMethod(ByVal typeName As String, ByVal methodName As String)
    'Get the type of the class
    Dim calledType As Type = Type.[GetType](typeName)

    'Invoke the method itself
    calledType.InvokeMember(methodName, BindingFlags.InvokeMethod Or BindingFlags.[Public] Or BindingFlags.[Static], Nothing, Nothing, Nothing)
End Sub

您只需将包含您要调用的方法的类的名称作为typeName传递,并将要调用的方法名称本身作为methodName传递:< / p>

InvokeStringMethod("MyClass", "Two")