我试图在添加到列表时通过其构造函数创建一个T类型的新对象。
我得到一个编译错误:错误消息是:
'T':创建变量实例时不能提供参数
但是我的类确实有构造函数参数!我该怎么做呢?
public static string GetAllItems<T>(...) where T : new()
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
tabListItems.Add(new T(listItem)); // error here.
}
...
}
这在你的情况下行不通。你只能指定一个构造函数为空的约束:
public static string GetAllItems<T>(...) where T: new()
你可以通过定义这个接口来使用属性注入:
public interface ITakesAListItem
{
ListItem Item { set; }
}
然后你可以改变你的方法如下:
public static string GetAllItems<T>(...) where T : ITakesAListItem, new()
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
tabListItems.Add(new T() { Item = listItem });
}
...
}
另一种替代方法是JaredPar描述的Func方法。