C # Dynamic Application and Newtonsoft.Json

Dynamic keyword in C #

dynamic keyword and dynamic language runtime (DLR) is a .Net 4.0 new features.

What is a "dynamic"?

  Programming language can sometimes be divided into statically typed language and dynamically typed languages. C # and Java are often believed to be static typed language, and Python, Ruby and JavaScript is a dynamically typed language.

  In general, the type of dynamic language will not be checked at compile time, but at run-time type identification of the object. Pros and cons of this approach: write up code faster and easier, but can not get a compiler error, only to ensure application uptime through unit testing and other methods.

  C # was originally created as a purely static language, but C # 4 adds some dynamic elements for improved interoperability between dynamic languages ​​and frameworks. C # design team considered several options, but the final OK to add a new keyword to support these features: dynamic.

  dynamic keyword can act as a static type declarations C # type system. In this way, C # will get dynamic features while still a statically typed language exists.

  Since the compile-time type checking will not go, so the IDE IntellSense lead to failure.

dynamic, Object or Var?

  So, what is the actual difference between the dynamic, Object and var that? When to use them?

  Let us talk about var, often someone will take dynamic and var comparison. In fact, var and dynamic entirely different concept, simply should not be placed together for comparison.

  var actually thrown our compiler syntactic sugar, once compiled, the compiler will automatically match the actual type of variable var, and replaced with the actual type of the declared variable, the equivalent to the actual use in coding type declaration. After being compiled and is a dynamic type Object, without checking the type of the dynamic compiler time.

  Let me say Object, after the above-mentioned types of dynamic recompilation is an Object type, the same type Object, then what is the difference between the two is it?

  In addition to whether the type checking at compile time, another important difference is the type of conversion, which is also dynamic place great value, conversion between instances instances of dynamic type and other types is very simple, developers can very easily switch between dyanmic and non-dynamic behavior. Any example can implicitly convertible to type dynamic example, see the following example:

D1 =. 7 dynamic;
dynamic D2 = "A String";
dynamic D3 = System.DateTime.Today;
dynamic System.Diagnostics.Process.GetProcesses D4 = ();
 
vice versa, in any type of expression can be dynamic implicit convert to other types.
D1 = I int;
String STR = D2;
the DateTime dt = D3;
the System.Diagnostics.Process [] = procs D4;

C # using dynamic types to access objects JObject

is C # inside dynamic dynamic type, access to the corresponding properties in the case of an unknown type, is very flexible and convenient.

Use Json.Net can be converted into a string JObject a Json object, if there is a known strong typing, if known type corresponding to strong, can be converted directly to the corresponding type. But if there is no time to access Json inside corresponding data, it is too much trouble. We can access the corresponding property by means of DynamicObject.

DynamicObject

We want to create a dynamic class for accessing JObject, code is as follows:

 1 public class JObjectAccessor : DynamicObject
 2     {
 3         private JToken obj;
 4 
 5         public JObjectAccessor(JToken obj)
 6         {
 7             this.obj = obj;
 8         }
 9 
10         public override bool TryGetMember(GetMemberBinder binder, out object result)
11         {
12             result = null;
13             var val = obj?[binder.Name];
14             if (val == null) return false;
15             result = Populate(val);
16             return true;
17         }
18 
19         private object Populate(JToken token)
20         {
21             var val = token as JValue;
22             if (val != null) return val.Value;
23             else if (token.Type == JTokenType.Array)
24             {
25                 var list = new List<object>();
26                 foreach (var item in token as JArray)
27                 {
28                     list.Add(Populate(item));
29                 }
30 
31                 return list;
32             }
33             else return new JObjectAccessor(token);
34         }
35     }

Then you can start using it:

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             string json = @"{'name': '小明','contact': {'city': '上海','phone': '18888888888'},'shopping_list': [{'type': '笔记本','price': 7888}, {'type':'火车', 'price':1.5}]}";
 6             JObject jobj = JObject.Parse(json);
 7             dynamic obj = new JObjectAccessor(jobj);
 8 
 9             Console.WriteLine($"{obj.name}: {obj.contact.city} {obj.contact.phone}");
10             Console.WriteLine($"{obj.shopping_list[0].type}: {obj.shopping_list[0].price}");
11         }
12     }

Run the program, look at the output:

Guess you like

Origin www.cnblogs.com/linxmouse/p/11847614.html