未找到类型上的构造函数
本文关键字:构造函数 类型 | 更新日期: 2023-09-27 18:20:11
异常消息: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个使用它的类,唯一的区别是输入的数量。
这是因为您使用的Activator.CreateInstance
重载接受一个对象数组,该数组应该包含一个构造函数参数列表。换句话说,它试图找到一个StateLog
构造函数重载,它有16个参数,而不是一个。这是由于数组协方差而编译的。
因此,当编译器看到以下表达式时:
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 }));