简体   繁体   中英

Creating an instance of a generic type

I have created an each helper like described here: http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx/

Now there is a bussiness rule when there is no items, create a dummy item so the loop gets executed once. Below the foreach statement I add the following:

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)));

The questions marks I want to create a dummy object of type T, when searching I found Activator.CreateInstance() But im unable to get that working.

The question I have, first is this the best approach to resolve it, to have it executed once create a dummy object like suggesting above here. If so how would I create the dummy object then ?

One approach would be to use the new constraint for T here. So, for example, the class or method here that defines T needs to add a constraint like this:

where T : new()

Please note that you must have a parameterless constructor on T , and it cannot be abstract :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM