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

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

问题描述

添加到列表时,我正在尝试通过其构造函数创建一个 T 类型的新对象.

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': 创建变量实例时无法提供参数

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

推荐答案

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

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

你可以这样称呼它

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

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

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