vendredi 8 décembre 2017

Extract type of object to use as generic

I have a class VResult<T> that can be instantiated with

bool value = true;    
VResult<bool> vr =  new VResult<bool>(value);

If I don't know the type of value, I'd like to do something like

VResult<typeof value> = new VResult<typeof value>(value);

Is that possible?

The ultimate goal is to serialize/deserialize VResult<T>:

string json = JsonConvert.SerializeObject(new VResult<bool>(true));

where could be an object or basic datatype such as int or bool.

I'm using a data transfer object that adds

ValueTypeName = Value.GetType().Name;

and

ValueTypeNamespace = Value.GetType().Namespace;

properties so that on the receiving side I can use

JObject obj = JObject.Parse(json);
string vt = (string)obj["ValueTypeName"];
string vtn = (string)obj["ValueTypeNamespace"];
Type type = Type.GetType($"{vtn}.{vt}");
var value = Activator.CreateInstance(type);
VResult<typeof value> vr = new VResult<typeof value> (value); //not correct

to get all the Type information about value, but I just don't figure out how to get the generic <T> from value to pass it in the VResult<T> constructor;





Aucun commentaire:

Enregistrer un commentaire