问题
I'm not sure if I don't get the big picture or if I just miss something but what are the benefits of parsing a JSON-String to a dynamic object?
If I have a class like this
class Product
{
public string Name { get; set; }
public double Price { get; set; }
public string Category { get; set; }
}
and I use the HttpClient to get the object like this
Product product = await response.Content.ReadAsAsync<Product>();
What do I benefit from this code?
string content = await response.Content.ReadAsStringAsync();
dynamic product = JObject.Parse(content);
If I want to use them I need to write
product.Name
With the strongly typed apporach I at least have the intellisense. If the service changes the Product the dynamic approach doesn't help me either because I still need to access it like I mentioned above.
So what am I missing? Why should I use dynamics or when?
回答1:
You will always prefer to use a strong type over a dynamic (performance\convenience).
Here are some cases you would like to use a dynamic:
When you want to parse an xml and dont want to work with XElement's, XPath's etc.
COM interop - It makes things really easy and nice (try working with Excel\Word and you will be convinced).
In some cases it's nicer and readable to use a dynamic instead of reflection.
来源:https://stackoverflow.com/questions/31118624/json-to-dynamic-object-vs-strongly-typed-object