2013-07-31 52 views
0

確定我確實有這樣的從方法列表

Public NotInheritable Class Helper 

    Private Function A(a As String) as Boolean 
     Return True 
    End Function 

    Private Function B(a As String) as Boolean 
     Return True 
    End Function 

End Class 

類現在,我想通過串名字來稱呼它,我想調用類中的方法來得到裏面的方法列表我的實例化的類(如果它可以作爲一個數組,它是細被返回)

Dim h as New Helper() 
'So it will list something like this 
'[0] - A 
'[1] - B 

的對象和我想要獲取的第二方法的名稱(其爲方法),並使用稱之爲它的名字是

Dim methodObj As MethodInfo 
methodObj = Type.GetType("Common.Validation.Helper").GetMethod(ReturnAFunction(1)) 
methodObj.Invoke(New Helper(), params)) 

這是可能的嗎?如果不是,我怎麼能靠近我想要的東西?感謝

回答

4

鑑於實例h

Dim h as New Helper() 

您可以使用GetMethods()

Dim yourPrivateMethods = h.GetType() _ 
          .GetMethods(BindingFlags.NonPublic Or BindingFlags.Instance) _ 
          .Where(Function(m) Not m.IsHideBySig) _ 
          .ToArray() '' array contains A and B 

'' get the method named 'B' and call it  
yourPrivateMethods.Single(Function(m) m.Name = "B").Invoke(h, {"the parameter"}) 

或者乾脆GetMethod(name)

h.GetType().GetMethod("B", BindingFlags.NonPublic Or BindingFlags.Instance).Invoke(h, {"the parameter"}) 

需要注意的是,因爲你的方法是私人的,你必須使用適當的BindingFlags

+0

它返回一個錯誤'System.String'類型的對象不能轉換爲類型'System.Char'.'指向'h'變量使用你說的第二種方式,因爲我使用私有方法 –

+0

@Mahan我的代碼中的任何地方都不使用'Char',也不會在你的問題中的任何地方使用'Char'。所以,顯然你嘗試在你的* real *代碼中將一個類型爲'String'的參數傳遞給一個具有'Char'類型參數的方法。也許你正在尋找類似'.Invoke(h,{「X」c}''你知道'String'和'Char'之間的區別嗎? – sloth

+0

@Mahan如果你有一個特定的問題,它重現它,也許使用[ideone](http://ideone.com/rPLH7i) – sloth