dimanche 22 juillet 2018

Invoke a Func object using reflection and a Type that's known at runtime

I've been trying to wrap my head around handling this scenario. The various similar (but not specifically the same) questions I've browsed on SO hasn't quite led me to where I'd like.

I have a situation where I have a Type and an object of type Func<string, (bool, T)> where T matches the Type. I'd like to be able to, via reflection or other means, call its Invoke method.

I have some Type at runtime:

Type type;

I have the Func in memory, but as an object:

object func;

The underlying Type of func is what I described earlier. For example, if type represents DateTime, then func's underlying type would be:

Func<string, (bool, DateTime)>

But type can be anything at runtime, so if it was instead an int, then func would now be a

Func<string, (bool, int)>

How can I use the fact that I have the correct type at runtime, to invoke my func? I'm assuming I have to use reflection of some sort but don't really understand it well enough to get started.

Any help is greatly appreciated.

I'm pretty new to reflection in general but I'm finding it very interesting and pretty difficult for some things. If you have any recommendations on readings or any other tips on how to better learn about reflection that'd be sweet as well!





Aucun commentaire:

Enregistrer un commentaire