Reputation: 7042
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.
Upvotes: 3
Views: 836
Reputation: 14734
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 );
Upvotes: 3