简体   繁体   中英

Converting a generic object to a strongly typed T

I am trying to write a method that will take a generic object and convert it into a type of T . The context is, I've just made a REST API call and I have the content of the response in value . In THIS case, I happen to know that the return type is an array of strings.

在此处输入图片说明

But of course, that won't always be the case.

using (var response = await client.SendAsync(request))
{
    HttpContent result = response.Content;
    object value = ((ObjectContent)result).Value;

    List<string> list = GenericToStronglyTyped<List<string>>(value);
    List<string> list2 = GenericToStronglyTyped_v2<List<string>>(value);
}

I found a similar question here that seemed positive: Cast object to T

And I tried the suggested answer as follows:

private T GenericToStronglyTyped<T>(object obj)
{
    if (obj is T)
    {
        return (T)obj;
    }
    try
    {
        return (T)Convert.ChangeType(obj, typeof(T));
    }
    catch (InvalidCastException)
    {
        return default(T);
    }
}

However, this returns null because of:

Object must implement IConvertible.

So I came up with my own solution:

private T GenericToStronglyTyped_v2<T>(object obj)
{            
    try
    {
        string json = JsonConvert.SerializeObject(obj);
        return JsonConvert.DeserializeObject<T>(json);
    }
    catch (InvalidCastException)
    {
        return default(T);
    }
}

That DOES work, but it feels like a bit of a gimmick. What is the best way to go about this?

Thanks!

That DOES work, but it feels like a bit of a gimmick. What is the best way to go about this?

I feel that you're venturing into opinion here, but, here's mine: the solution you've presented as being gimmicky is both well-tested and extremely easy to read. I'll take those all day long.

If at some point the serialization is too much overhead, then come back and take a closer look. But especially when shunting stringy data around, there are just too many edge cases to consider. This is a solved problem, so I'd recommend appreciating that those libraries exist and moving on to your actual business logic.

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