2015-02-24 33 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

相关问题