2014-01-18 2 views
4

이름으로 매개 변수의 값을 동적으로 가져 오는 방법을 아는 사람이 있습니까? 동적으로 매개 변수를 전달하는 함수를 작성하려고합니다. Reflection을 사용하여 매개 변수의 이름을 가져 왔지만 함수에 전달 된 값을 가져 오는 방법을 파악할 수 없습니다.이름으로 변수 값 가져 오기

예 :

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

속성을 반환합니다 다음 방법 (주어진 속성 이름) 값 : 당신은 'XYZZY'을 인쇄하려면

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

희망이 도움 then


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