小编典典

将参数传递给模板类型的C#通用new()

c#

添加到列表中时,我试图通过其构造函数创建一个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.
   } 
   ...
}

阅读 845

收藏
2020-05-19

共1个答案

小编典典

为了在函数中创建泛型类型的实例,您必须使用“ new”标志对其进行约束。

public static string GetAllItems<T>(...) where T : new()

但是,这仅在您要调用没有参数的构造函数时才有效。这里不是这样。相反,您必须提供另一个参数,该参数允许基于参数创建对象。最简单的是功能。

public static string GetAllItems<T>(..., Func<ListItem,T> del) {
  ...
  List<T> tabListItems = new List<T>();
  foreach (ListItem listItem in listCollection) 
  {
    tabListItems.Add(del(listItem));
  }
  ...
}

然后可以这样称呼它

GetAllItems<Foo>(..., l => new Foo(l));
2020-05-19