Passing arguments to C# generic new() of templated type(将参数传递给模板类型的 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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将参数传递给模板类型的 C# 泛型 new()


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01