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()
基础教程推荐
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
