c# - How do I design a generic method with a new() constraint if it's only taking in non-concrete objects? -


i'm having trouble designing system creates instances prototype object. here's have:

dictionary<type, ifoo> prototypes; object createinstance(type type) {     ifoo value;     if (!prototypes.trygetvalue(type, out value))     {         value = activator.createinstance(type) ifoo;         prototypes.add(type, value);     }     return create(value object); }  t create<t>(t instance) t : new() {     return new t(); // returns new blank object } 

i know problem can't guarantee these objects have parameterless constructor. can then? there's no way specify in ifoo have parameterless constructor, there? thing can think of have simple create() function specified in ifoo, hoping there'd solution doesn't involve injecting ton of new boilerplate code codebase.

and can't call activator.createinstance() every time, because of performance issues (i'll running function lot).

thanks suggestions.

the problem generics compile-time feature. trying create objects type determined @ run-time.

therefore, can't use generics this.

when call create(value object);, type parameter t object (because it's inferred @ compile-time compile-time type of argument), new object() returned.

you call create<foo> , foo instance, there's no way take type type , call appropriate create<type> without heavy use of reflection.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -