C
C#3y ago
DeaDo

Is there a good way to use a object from Type Type in a generic method?

Type type = typeof(object);
GenericMethod</*use Type here*/>();
Type type = typeof(object);
GenericMethod</*use Type here*/>();
I have a lot of serialized different Objects in a Database along with their typename as string. All of them share the same Interface. Now i want to deserialize all of those to the right Objects. Therefore i created a Application scanner that collects the Types for all those objects. Now i want to compare the typenames and deserialize them in a loop. All of this feels wrong.
private IInterface GetObject(StoredObject storedObject)
{
foreach(var type in TypeList)
{
if(type.Name == storedObject.Type)
return JsonConvert.DeserializeObject</*TheCorrectType*/>(storedObject.ActualObjectData);
}
}
private IInterface GetObject(StoredObject storedObject)
{
foreach(var type in TypeList)
{
if(type.Name == storedObject.Type)
return JsonConvert.DeserializeObject</*TheCorrectType*/>(storedObject.ActualObjectData);
}
}
sth. like this
7 Replies
DeaDo
DeaDoOP3y ago
the storedObject contains the typename as string and the actual object as string
mtreit
mtreit3y ago
There is a non generic overload that takes the Type object as a method parameter. If you can have a mapping of strings to the actual type objects (like a dictionary or even just a switch expression) you can use that maybe?
Angius
Angius3y ago
Generics need to be known at compile time
mtreit
mtreit3y ago
Not if you're willing to write very gnarly reflection code when
Angius
Angius3y ago
Shhh
mtreit
mtreit3y ago
But yes generally don't do that
DeaDo
DeaDoOP3y ago
Thx.
Want results from more Discord servers?
Add your server