2015-05-05 21 views
1

使用VB.Net 4和VS2012如何從字符串變量調用子程序?

我有這樣的在它的一些邏輯模塊:

Module Mod1 
    If x = 1 then 
     Mod2("Mod3","save_it") 
    else 
     Mod2("Mod4","edit_it") 
    end if 
End Module 

Module Mod2(which_mod, which_action) 
    ' call the correct subroutine 
    which_mod.which_action() 
End Module 

如何使用字符串來調用不同的模塊正確的子程序?

+0

在什麼語言是有效的語法?這當然不是VB.NET。你不能將邏輯添加到模塊主體,你必須使用一種方法。 –

+0

你爲什麼要這麼做?你的基本需求是什麼? – Enigmativity

+1

@Enigmativity我同意。這看起來像[XY問題](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/66378#66378)。 –

回答

0

看看System.Reflection命名空間,它包含一個名爲MethodInfo的類。

您可以獲取MethodInfo的,對於給定對象,使用方法名,然後調用它:

Dim method As MethodInfo = obj.GetType().GetMethod(methodName, BindingFlags.Instance Or BindingFlags.Public) 
method.Invoke() 
0

source

有一個功能CallByName這正是這麼做的。

該函數接受4個參數:

  • 對象/類

  • 功能/ PROCNAME

  • CALLTYPE(CallType.method,CallType.Get,CallType.Set)

  • (可選):參數(在數組格式中)

第一個參數(對象/類)不能是字符串,所以我們必須將您的字符串轉換爲對象。要做到這一點,最好的辦法是

Dim MyInstance As Object = Activator.CreateInstance(Type.GetType(which_mod)) 

因此,對於你的代碼:

Imports Microsoft.VisualBasic.CallType 
Imports System.Reflection 
Class Mod1 
    If x = 1 then 
     Mod2("Mod3","save_it") 
    else 
     Mod2("Mod4","edit_it") 
    end if 
End Class 

Module Mod2(which_mod, which_action) 
    ' call the correct subroutine 
    Dim MyInstance As Object = Activator.CreateInstance(Type.GetType(which_mod)) 
    CallByName(MyInstance , which_action, CallType.Method) 
End Module 
+0

非常接近。 'which_mod'變量是一個'Object'而不是'String'。 – Enigmativity

+0

@Enigmativity你是對的,讓我們來看看我們如何才能施展它。 – Jordumus

+0

這就是字符串到對象的字典將會出現的地方。需要從字符串中進行某種對象查找。 – Enigmativity