2014-02-18 50 views
0

我創建了一個叫做input實例,它是類型:C#反射調用 - 類型「XXX」的對象不能轉換爲類型「System.Object的[]」

public class TestInput 
{ 
    public int TesTInt { get; set; } 
} 

我在這個函數中使用:

public static class TestClass 
{ 
    public static string TestFunction() 
    { 
     var testInput = new TestInput(); 
     string res = ServicesManager.Execute<string>((object) testInput); 

     return res; 
    } 
} 

Execute功能是在這裏:

public static OUT Execute<OUT>(object input) 
      where OUT : class 
{ 
     var method = //getting method by reflection 
     object[] arr = new object[] { input }; 
     return method.Invoke(null, arr) as OUT; //Error is triggered here 
} 

,我調用是THI的方法s:

public static string TestFunctionProxy(object[] input) 
{ 
     var serviceInput = input[0] as TestInput; 
     //rest of code 
} 

我在標題中收到錯誤。 (XXX - 「TestInput」類型)

發生了什麼以及是什麼導致了此錯誤?

注意:method是靜態的,因此第一個參數不需要實例。如果我錯了,請糾正我。

任何幫助表示讚賞。

編輯:用一些更多的代碼更新了問題的完整例子。

+0

如果您提供了一個簡短的*完整的*示例,那將會更容易幫助您。我也懷疑錯誤消息中沒有包含「XXX」。我們不知道你在哪裏得到錯誤... –

+0

@JonSkeet不夠公平,會更新問題。 –

+0

將對象作爲對象並將其轉換爲對象的對象是兩件不同的事情。您的方法期望獲得哪些*精確*參數類型? – Crono

回答

5

您正在向該方法傳遞錯誤的參數。它需要一個對象[],並且你正在給一個simpe對象。這是如何解決此問題:

object[] arr = new object[] { new object[] { input } }; 

的「外部」對象[]是用於調用參數,所述「內部」陣列對於你的方法的參數。

+0

非常好,非常感謝。 –

相關問題