开发者

Calling a method when the method name is contained in a string

开发者 https://www.devze.com 2023-04-11 05:42 出处:网络
Let\'s say I have a page Test.aspx along with test.aspx.vb. Test.aspx.vb contains a class name \"TestClass\". In that class I have method1(), method2() and method3()

Let's say I have a page Test.aspx along with test.aspx.vb.

Test.aspx.vb contains a class name "TestClass". In that class I have method1(), method2() and method3()

I need to be able to call one of those methods, but I can't hard code it, the method to be executed comes from a string.

I can't do

Select Case StringContainingTheNameOfTheDesiredMethod
    Case "Method1" 
        Method1()
    Case "Method2"
       Method2()
end case

.

That I could find how to do with reflection (I followed that example). My problem is that those methods might need to interact with test.aspx, but when I use .invoke it seems to create a new thread or context and any reference to test.aspx becomes null (setting label1.text = "something" will generate a null reference, but a direct call 开发者_运维问答of method1 (without invoke) will update label1.text just fine.

Is there any solution ? Can anyone give me some tips?


You need to pass an instance of Test page to Invoke method (so you invoke it on the object). Sorry for C# code ;-)

MethodInfo method = typeof(TestPage).GetMethod(StringContainingTheNameOfTheDesiredMethod);
method.Invoke(this, null);


    Dim xAssembly As Assembly = Assembly.GetExecutingAssembly()

    Dim xClass As Object = xAssembly.CreateInstance("Paradox.Intranet2.ManageUsers", False, BindingFlags.ExactBinding, Nothing, New Object() {}, Nothing, Nothing)
    Dim xMethod As MethodInfo = xAssembly.GetType("Paradox.Intranet2.ManageUsers").GetMethod("TestCallFromString")

    Dim ret As Object = xMethod.Invoke(Me, New Object() {})
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号