Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Use a Type found via reflection as a generic [duplicate]

I am attempting to use a Type as a generic. Essentially, I'm able to find a Type based off it's signature using reflection. I now need to do something like this:

Type theType = this.getMyType(mySignature);
string convertedData = mappingObj.mapIt<DataBase, theType>(myData);

However, I cannot use theType as a generic. Is there a way to do this?

EDIT: Following suggestion by Sohaib Jundi, I run into the following (the non simplified code is working with Automapper's Map method):

typeof(IMapper).GetMethod("Map")

That line yields this error:

'typeof(IMapper).GetMethod("Map")' threw an exception of type 'System.Reflection.AmbiguousMatchException'

The method I'm attempting to get with GetMethod is Map<TDestination, TSource>(TSource source), but I cannot determine the method signature to call to get that method. For reference, here is the link to automappers IMapper class, where the Map method lives.

AutoMapper IMapper

like image 404
steventnorris Avatar asked Mar 04 '23 18:03

steventnorris


1 Answers

You can also use reflection to invoke the generic method. It would be something like this:

string convertedData = (string)mappingObj.GetType().GetMethod("mapIt")
    .MakeGenericMethod(typeof(DataBase), theType).Invoke(mappingObj, new object[] { myData });
like image 80
Sohaib Jundi Avatar answered Mar 15 '23 02:03

Sohaib Jundi