2012-01-08 2 views
33

MethodInfo.Invoke을 사용하여 매개 변수를 참조로 전달할 수 있습니까? MethodInfo.Invoke를 사용하여 매개 변수를 참조로 전달하는 방법

내가 전화 할 방법 :

private static bool test(string str, out byte[] byt) 

나는이 시도하지만 실패 : 반환

byte[] rawAsm = new byte[]{}; 
MethodInfo _lf = asm.GetTypes()[0].GetMethod("test", BindingFlags.Static | BindingFlags.NonPublic); 
bool b = (bool)_lf.Invoke(null, new object[] 
{ 
    "test", 
    rawAsm 
}); 

바이트는 null입니다.

답변

44

먼저 인수 배열을 만들고이 배열에 대한 참조를 유지해야합니다. out 매개 변수 값이 배열에 저장됩니다. 그래서 당신은 사용할 수 있습니다

object[] arguments = new object { "test", null }; 
MethodInfo method = ...; 
bool b = (bool) method.Invoke(null, arguments); 
byte[] rawAsm = (byte[]) arguments[1]; 

주 그것이 out 매개 변수이기 때문에 당신이, 두 번째 인수에 대한 값을 제공 할 필요가 없습니다 방법 - 값이 방법으로 설정됩니다. 매개 변수가 out이 아닌 ref 인 경우 초기 값이 사용되지만 배열의 값은 여전히 ​​메서드로 대체 될 수 있습니다.

짧지 만 완전한 샘플 :

using System; 
using System.Reflection; 

class Test 
{ 
    static void Main() 
    { 
     object[] arguments = new object[1]; 
     MethodInfo method = typeof(Test).GetMethod("SampleMethod"); 
     method.Invoke(null, arguments); 
     Console.WriteLine(arguments[0]); // Prints Hello 
    } 

    public static void SampleMethod(out string text) 
    { 
     text = "Hello"; 
    } 
} 
11

반사에 의해 호출하는 방법이가 다시 인수 목록으로 사용 된 배열에 복사됩니다 ref 매개 변수가 있습니다. 복사 된 역 참조를 얻으려면 인수로 사용 된 배열을 살펴보기 만하면됩니다.

object[] args = new [] { "test", rawAsm }; 
bool b = (bool)_lf.Invoke(null, args); 

이 호출 args[1] 새로운 byte[]

있을 것이다 후