找不到类型的构造函数

exception消息: Constructor on type StateLog not found

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

  List list = new List(); 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个类,唯一的区别是输入数量。

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

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

 Activator.CreateInstance(typeof(T), lines) 

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

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

然后,该方法将尝试查找一个构造函数,该构造函数具有等于lines.Length所有类型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数组作为第一个数组项传递,有效:

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

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

 list.Add((T)Activator.CreateInstance(typeof(T), new object[] { lines }));