Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type using reflection to feed to generic class

Tags:

c#

reflection

How do I get the class name/type using the class name string? like

Dictionary<string, string> DFields = GetFields();

the type is

Dictionary<string, string>
object = Deserialize<?>(_stream)

Ideally, I was thinking:

object = Deserialize<"Dictionary<string, string>">(_stream)

It should become

object = Deserialize<Dictionary<string, string>>(_stream) 

in order to work. Im serializing like 10 object but I only have the type names in string format. I need to format the string format to actual type so I can feed it to the generic serializer deserializer function.

like image 765
iefpw Avatar asked Dec 20 '25 18:12

iefpw


1 Answers

Step 1 - Get type instance:

You need to use an assembly qualified name passed into Type.GetType(). Doing a quick test by calling GetType().AssemblyQualifiedName on a Dictionary() type instance, it turns out to be:

System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

quite a mess. I believe you can remove most of it though and it'll still work:

System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.String, mscorlib]], mscorlib

therefor:

var typeName = "System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.String, mscorlib]], mscorlib";
var type = Type.GetType( typeName );

Step 2 (assuming the API forces a generic parameter which IMO is shit) - Use reflection to parametize the generic method dynamically:

var genericMethod = typeof(Serialzier).GetMethod( "Deserializer" );
var parametizedMethod = genericMethod.MakeGenericMethod( type );
var parameters = new object[] { _stream };
var deserializedInstance = parametizedMethod.Invoke( null, parameters );
like image 103
Tyson Avatar answered Dec 22 '25 10:12

Tyson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!