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()
基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
