简体   繁体   中英

Extract type of object to use as generic <T>

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);
value = obj["Value"];
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;

You can create the generic instance like this:

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 });

And now you have a instance of VResult<int> with a value of 1 . Is this what you were looking for?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM