找不到类型的构造函数

Jac*_*ert 27 c# constructor constructor-exception

例外消息:Constructor on type StateLog not found.

我有以下代码,不适用于只有一个类:

        List<T> list = new List<T>();
        string line;
        string[] lines;

        HttpWebResponse resp = (HttpWebResponse)HttpWebRequest.Create(requestURL).GetResponse();

        using (var reader = new StreamReader(resp.GetResponseStream()))
        {
            while ((line = reader.ReadLine()) != null)
            {
                lines = line.Split(splitParams);
                list.Add((T)Activator.CreateInstance(typeof(T), lines));
            }
        }
Run Code Online (Sandbox Code Playgroud)

它不起作用的类的构造函数与它工作的其他类完全相同.唯一的区别是这个类将传递16个参数而不是2-5.构造函数看起来像这样:

    public StateLog(string[] line)
    {
        try
        {
            SessionID = long.Parse(line[0]);
            AgentNumber = int.Parse(line[1]);
            StateIndex = int.Parse(line[5]);
            ....
        }
        catch (ArgumentNullException anex)
        {
            ....
        }
    }
Run Code Online (Sandbox Code Playgroud)

就像我说的,它适用于使用它的其他5个类,唯一的区别是输入的数量.

Gro*_*roo 47

那是因为你正在使用接受一个对象数组的Activator.CreateInstance重载,它应该包含一个构造函数参数列表.换句话说,它试图找到一个StateLog构造函数重载,它有16个参数,而不是一个.这由于阵列协方差而编译.

所以当编译器看到这个表达式时:

Activator.CreateInstance(typeof(T), lines)
Run Code Online (Sandbox Code Playgroud)

因为它lines是a string[],它假设你想依靠协方差将它object[]自动转换为,这意味着编译器实际上看起来像这样:

Activator.CreateInstance(typeof(T), (object[])lines)
Run Code Online (Sandbox Code Playgroud)

然后,该方法将尝试找到一个构造函数,该构造函数具有等于lines.Length所有类型的多个参数string.

例如,如果您有这些构造函数:

class StateLog
{
      public StateLog(string[] line) { ... }
      public StateLog(string a, string b, string c) { ... }
}
Run Code Online (Sandbox Code Playgroud)

调用Activator.CreateInstance(typeof(StateLog), new string[] { "a", "b", "c" })将调用第二个构造函数(具有三个参数的构造函数),而不是第一个构造函数.

你真正想要的是有效地将整个lines数组作为第一个数组项传递:

var parameters = new object[1];
parameters[0] = lines;
Activator.CreateInstance(typeof(T), parameters)
Run Code Online (Sandbox Code Playgroud)

当然,您可以简单地使用内联数组初始值设定项:

list.Add((T)Activator.CreateInstance(typeof(T), new object[] { lines }));
Run Code Online (Sandbox Code Playgroud)

  • 它有一个重载,接受16个字符串`参数?:) (2认同)
  • 我得到你现在说的话.它的参数数量很重要.如果我睡了3个多小时,我可能会早点得到它. (2认同)