Skip to main content
 首页 » 编程设计

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

2024年02月06日15jackei

我创建了一个 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 的约束。因此,例如,此处定义 T 的 class 或 method 需要添加这样的约束:

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.