2014-01-18 149 views
4

有誰知道有任何方法通過名稱動態獲取參數的值嗎?我試圖創建一個動態傳遞參數的函數。我使用反射來獲取參數的名稱,但似乎無法弄清楚如何獲取傳遞給該函數的值。按名稱獲取變量值

例子:

Imports System.Reflection 

Console.WriteLine(Test("Xyzzy")) 
' Should print: Xyzzy 

Function Test(ByVal x as String) 
    Return GetValueByName(MethodBase.GetCurrentMethod.GetParameters(0).Name)) 
End Function 
+2

你可以給一個bette例如,也許它背後的目標?在這種情況下,我會說:返回x的值 –

+2

目前在.NET中不可能。請參閱[這個問題](http://stackoverflow.com/questions/1867482/c-sharp-getting-value-of-parms-using-reflection) –

+0

如果這個代碼將*內* *相同的方法,你想檢查,那麼肯定它不需要動態?作爲該方法的作者,您已經知道所有參數。 – nmclean

回答

0

下面的方法將返回屬性(給出的屬性名)值:

Public Function GetPropertyValue(propertyName As String) As Object 

     Dim pi As System.Reflection.PropertyInfo = Me.GetType().GetProperty(propertyName) 

     If (Not pi Is Nothing) And pi.CanRead Then 
      Return pi.GetValue(Me, Nothing) 
     End If 

     Dim a As Type() = Nothing 
     Dim mi As System.Reflection.MethodInfo = Me.GetType().GetMethod("Get" + propertyName, a) 

     If Not mi Is Nothing Then 
      Return mi.Invoke(Me, Nothing) 
     End If 

     Return Nothing 
    End Function 

希望它可以幫助

0

如果你想打印 'XYZZY'那麼


Console.WriteLine(Test("Xyzzy")) 
' Should print: Xyzzy 
Function Test(ByVal x as String) 
    Return x     
End Function