2015-02-24 32 views
0

我有以下的C#類和2層的構造函數:構造 'GTS.CSVImport_HR_Standard' 未找到

public class CSVImport_HR_Standard : CSVImport 
{ 
    int fPropertyID; 

    public CSVImport_HR_Standard() 
    { 
    } 

    public CSVImport_HR_Standard(string oActivationParams) 
    { 
     this.fPropertyID = Convert.ToInt32(oActivationParams); 
    } 

和父類:

public class CSVImport 
{ 

沒有任何構造函數。

類正在從下面的方法調用:

private object CreateCommandClassInstance(string pCommandClass, string pActivationParams.ToArray()) 
    { 
     List<object> oActivationParams = new List<object>(); 
     // In the current implementation we assume only one param of type int 
     if (pActivationParams != "") 
     { 
      Int32 iParam = Convert.ToInt32(pActivationParams); 

      oActivationParams.Add(iParam); 
     } 


     object oObject = Activator.CreateInstance(Type.GetType("GTS." + pCommandClass), oActivationParams); 

     return(oObject); 
    } 

pCommandClass = GTS.CSVImport_HR_Standard 

,但我得到了以下錯誤:

Constructor on type 'GTS.CSVImport_HR_Standard' not found. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
Exception Details: System.MissingMethodException: Constructor on type 'GTS.CSVImport_HR_Standard' not found. 

至於我能看到構造函數是正確的,它傳遞了所有正確的參數,那爲什麼它給了我這個錯誤?

從我讀過,我最好的猜測是,這是值得做的線:

object oObject = Activator.CreateInstance(Type.GetType("GTS." + pCommandClass), oActivationParams); 

但我不知道什麼可能會造成一個問題,因爲它似乎在構造函數是正確的?

回答

1

您的主要問題是使用List<object>作爲CreateInstance方法中的第二個參數。這使得該方法搜索一個簽名爲(List<object>)的構造函數,而不是內部元素的類型。

你必須調用ToArray爲了調用該方法的正確的過載(它現在調用:

object oObject = Activator.CreateInstance(Type.GetType("GTS." + pCommandClass) 
             , oActivationParams.ToArray() 
             ); 

此外,請務必使用if (!string.IsNullOrEmpty(pActivationParams))代替if (pActivationParams != "")

+0

我已經試過了,但它不工作 – Alex 2015-02-24 13:05:12

+1

你試試我的最後一個音符?嘗試將'pActivationParams'設置爲'null'。 – 2015-02-24 13:06:31

+0

是的,我嘗試使用ToArray,也改變了構造函數接收數組,但它仍然給出了相同的錯誤 – Alex 2015-02-24 13:12:01

0

的問題了。它將數組轉換爲參數列表並將它們單獨傳遞。

解決方法我使用構造函數完成了以下操作:

public CSVImport_HR_Standard(params object[] oActivationParams) 
    { 
     this.fPropertyID = Convert.ToInt32(oActivationParams[0]); 
    } 

,並通過了如下:

object oObject = Activator.CreateInstance(Type.GetType("GTS." + pCommandClass), oActivationParams.ToArray()); 
+0

爲什麼你要使用'params'?自從將一個數組傳遞給'CreateInstance'方法,似乎沒有用... – 2015-02-24 13:42:19

+0

如果要使用帶有字符串oActivationParams的構造函數,則需要傳入一個「字符串」,而不是將其轉換爲你的'CreateCommandClassInstance'方法中的整數。 – 2015-02-24 13:43:49

+0

@PatrickHofman @PatrickHofman這是現有的軟件,除構造函數以外的所有部分都被應用程序的其他部分使用,因此我無法改變任何內容,而這是我能夠使其工作的唯一方法。我非常感謝你的幫助。 – Alex 2015-02-24 13:46:06

相關問題