c# - IndexOutOfRangeException when trying to access the generic arguments of a Func<object> delegate -
i need generic argument type factory delegate (func<object
), results in indexoutofrangeexception
.
public void bind(type service, func<object> factory) { var factoryresulttype = factory.method.getgenericarguments()[0]; // ex } // extension public static void bind<tservice>(this ibinder binder, func<tservice> factory) tservice : class { binder.bind(typeof(tservice), (func<object>) factory); } // usage var dummyclass = new dummyclass(); binder.bind<idummy>(() => dummyclass);
a delegate func<t>
compiled along these lines:
public class func<t> { public t invoke() { /* ... */ } }
the methodinfo
returned factory.method
represents invoke
method above. can see, method not generic, , that's why code fails.
you could, instead, check return type:
var type = f.method.returntype;
or, @sszarek suggested, check type's generic arguments.