2012-05-28 70 views
0

全部我有一些C#DLL,我想在運行時使用System.Reflection從我的應用程序調用。我使用的核心代碼是一樣的東西通過反射將參數數組傳遞給C#DLL

DLL = Assembly.LoadFrom(Path.GetFullPath(strDllName)); 
classType = DLL.GetType(String.Format("{0}.{0}", strNameSpace, strClassName)); 
if (classType != null) 
{ 
    classInstance = Activator.CreateInstance(classType); 
    MethodInfo methodInfo = classType.GetMethod(strMethodName); 
    if (methodInfo != null) 
    { 
     object result = null; 
     result = methodInfo.Invoke(classInstance, parameters); 
     return Convert.ToBoolean(result); 
    } 
} 

我想知道我怎麼能參數數組中傳遞給DLL作爲ref,這樣我可以提取出來的DLL裏面發生了什麼信息。我想要什麼(但當然不會編譯)的清晰寫照將是

result = methodInfo.Invoke(classInstance, ref parameters); 

我該如何做到這一點?

+0

可能會有所幫助:http://stackoverflow.com/questions/1551761/ref-parameters-and-reflection – Dennis

回答

2

更改爲ref參數反映在您傳遞到MethodInfo.Invoke的數組中。你只需要使用:

object[] parameters = ...; 
result = methodInfo.Invoke(classInstance, parameters); 
// Now examine parameters... 

注意,如果有問題的參數是參數數組(根據您的標題),你需要用在arrayness的另一個層面:

object[] parameters = { new object[] { "first", "second" } }; 

至於CLR而言,這只是一個參數。

如果這沒有幫助,請給一個簡短而完整例子 - 你不需要使用單獨的DLL來證明,只需用Main方法的控制檯應用程序和方法,通過反射調用應沒事的。

+0

非常感謝喬恩。我以前正在做'result = methodInfo.Invoke(classInst,new object [] {dllParams});'但沒有意識到這就是我正在做的 - 一個成熟的。我會立即嘗試並回復你。感謝你的寶貴時間。 – MoonKnight