gpt4 book ai didi

c# - 创建泛型类型的实例

转载 作者:太空宇宙 更新时间:2023-11-03 21:28:10 24 4
gpt4 key购买 nike

我创建了一个 each 助手,如下所述:http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx/

现在有一个业务规则,当没有项目时,创建一个虚拟项目以便循环执行一次。在 foreach 语句下方,我添加了以下内容:

if (!items.Any()) {
var result = template(new IndexedItem<T>(1, ???));
result.WriteTo(writer);
}

//Fixed by doing:
var result = template(new IndexedItem<T>(1, default(T)));

问号我想创建一个 T 类型的虚拟对象,在搜索时我找到了 Activator.CreateInstance() 但我无法让它工作。

我的问题是,首先这是解决它的最佳方法,一旦创建了一个像上面建议的虚拟对象就执行它。如果是这样,我将如何创建虚拟对象?

最佳答案

一种方法是使用 new T 的约束。因此,例如,此处定义 Tclassmethod 需要添加这样的约束:

where T : new()

请注意,您必须T 上有一个无参数构造函数,并且它不能是抽象:

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.

关于c# - 创建泛型类型的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25723470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com