Retrieve the type of object to use as a generic <T>

I have a class VResult<T>that can be created using

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

If I do not know the type value, I would like to do something like

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

Is it possible?

The ultimate goal is serialization / deserialization VResult<T>:

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

where can be an object or a basic data type, for example intor bool.

I use a data transfer object that adds

ValueTypeName = Value.GetType().Name;

and

ValueTypeNamespace = Value.GetType().Namespace;

so 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);
value = obj["Value"];
VResult<typeof value> vr = new VResult<typeof value> (value); //not correct

to get all the information Typeabout value, but I just don’t understand how to get the general <T>out value, to pass it in the constructor VResult<T>;

+4
source share
1 answer

:

object value = 1; //I don't know the runtime type of this
var genericType = typeof(VResult<>).MakeGenericType(value.GetType());
var genericInstance = Activator.CreateInstance(genericType, 
                                               new object[] { value });

VResult<int> value 1. , ?

+3

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


All Articles