32

异常消息: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));
            }
        }

它不适用的类的构造函数与它适用的其他类完全相同。唯一的区别是这个类将传递 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)
        {
            ....
        }
    }

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

4

1 回答 1

61

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

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

Activator.CreateInstance(typeof(T), lines)

因为lines是 a string[],所以它假定您希望依靠协方差将其object[]自动转换为,这意味着编译器实际上是这样看待它的:

Activator.CreateInstance(typeof(T), (object[])lines)

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

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

class StateLog
{
      public StateLog(string[] line) { ... }
      public StateLog(string a, string b, string c) { ... }
}

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

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

var parameters = new object[1];
parameters[0] = lines;
Activator.CreateInstance(typeof(T), parameters)

当然,您可以简单地使用内联数组初始化器:

list.Add((T)Activator.CreateInstance(typeof(T), new object[] { lines }));
于 2014-08-29T23:55:50.647 回答