参数传递到模板类型的C#泛型新的() [英] Passing arguments to C# generic new() of templated type

查看:466
本文介绍了参数传递到模板类型的C#泛型新的()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过其构造函数添加到列表中,当创建类型T的新对象。

我得到一个编译错误:错误消息是:

  

'T':创建变量的实例时无法提供参数

不过我的课确实有一个构造函数参数!我怎样才能使这项工作?

 公共静态字符串GetAllItems< T>(...),其中T:新的()
{
   ...
   名单< T> tabListItems =新的名单,其中,T>();
   的foreach(列表项的listItem在listCollection)
   {
       tabListItems.Add(新T(的listItem)); //这里的错误。
   }
   ...
}
 

解决方案

为了创建一个通用型的功能,你必须用新的标志,限制它的一个实例。

 公共静态字符串GetAllItems< T>(...),其中T:新的()
 

但是,当你要调用它没有参数的构造只会工作。不是这里的情况下。相反,你得提供另一个参数,允许对象的基于参数的创建。最简单的是一个函数。

 公共静态字符串GetAllItems< T>(...,Func键<列表项,T>德尔){
  ...
  名单< T> tabListItems =新的名单,其中,T>();
  的foreach(列表项的listItem在listCollection)
  {
    tabListItems.Add(德尔(的listItem));
  }
  ...
}
 

您可以调用它像这样

  GetAllItems<富>(...,L =>新建美孚(1));
 

I'm trying to create a new object of type T via its constructor when adding to the list.

I'm getting a compile error: The error message is:

'T': cannot provide arguments when creating an instance of a variable

But my classes do have a constructor argument! How can I make this work?

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.
   } 
   ...
}

解决方案

In order to create an instance of a generic type in a function you must constrain it with the "new" flag.

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

However that will only work when you want to call the constructor which has no parameters. Not the case here. Instead you'll have to provide another parameter which allows for the creation of object based on parameters. The easiest is a function.

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

You can then call it like so

GetAllItems<Foo>(..., l => new Foo(l));

这篇关于参数传递到模板类型的C#泛型新的()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆