Get type using reflection to feed to the general class

How to get class name / type using class name string? as

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

a type

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

Ideally, I thought:

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

He must become

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

to work. I serialize as 10 objects, but I only have type names in string format. I need to format the string format to the actual type so that I can pass it to the universal function of the serializer deserializer.

+4
source share
1 answer

Step 1 - Get an instance of type:

You need to use the qualified assembly name passed to Type.GetType() . Performing a quick test by calling GetType().AssemblyQualifiedName in an instance of type Dictionary (), it turns out:

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 that you can remove most of them, although it will still work:

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

for this:

 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 common parameter that IMO is shit) - Use reflection to parameterize the dynamic generic method:

 var genericMethod = typeof(Serialzier).GetMethod( "Deserializer" ); var parametizedMethod = genericMethod.MakeGenericMethod( type ); var parameters = new object[] { _stream }; var deserializedInstance = parametizedMethod.Invoke( null, parameters ); 
+3
source

Source: https://habr.com/ru/post/1397949/


All Articles