c# - Getting generic value from fieldinfo throws exception: "Late bounds operation cannot be performed..." -
i'm trying instance value of generic type static field inside generic class, , throws exception:
late bound operations cannot performed on fields types type.containsgenericparameters true
public class managertemplate<q, t> : iobjectmanager t : filmation.runtime.engine.objectid, new( ) q : managertemplate<q, t>, new( ) { public readonly static q instance = new q( ); <---- static field } private static void findmanagers( ) { var iobjectmanagertype = typeof( iobjectmanager ); var managers = iobjectmanagertype.assembly .gettypes( ) .where( t => !t.isabstract && t.getinterfaces().any( => == iobjectmanagertype) ); foreach (var manager in managers) { var fi = manager.getfield( "instance" ); var instance = fi.getvalue( null ); <--- exception } }
i have tried use getgenerictypedefinition, continues throwing exception.
i have searched in google, have not found how can done...
anyone knows how can done?
edit: same using static property
this workaround have implemented, (though i'd know if can done using reflection):
public static q instance { get; private set; } static managertemplate( ) { instance = new q( ); environment.managers.add( instance ); }
you cannot value of public readonly static q instance = new q( );
generic type definition managertemplate<q, t>
, because there no concrete type q
.
how instance of generic type definition q
if not yet know concrete type q
is? simple: can't.
now... if want instance of type descends managertemplate<q, t>
generic type parameter q
defined, want exclude generic type parameters search.
private static ienumerable<iobjectmanager> findmanagers() { type type = typeof(iobjectmanager); ienumerable<type> managers = type.assembly .gettypes() .where(t => !t.isabstract && t.getinterfaces().contains(type)); foreach (type manager in managers) { var fi = manager.getfield("instance", bindingflags.public | bindingflags.static | bindingflags.flattenhierarchy); if (fi != null && !fi.fieldtype.isgenericparameter && type.isassignablefrom(fi.fieldtype)) { yield return (iobjectmanager) fi.getvalue(null); } } }
this "managers" defined in classes descend managertemplate<q, t>
have defined type q
is.
Comments
Post a Comment