What is the difference between var and dynamic and how to correctly use dynamic ?, Vardynamic
Many keywords in C # are easy to confuse. var and dynamic are one of them. They can declare dynamic variables, but they have many differences in nature. Var has determined the type in the compilation phase. during initialization, the initialization value must be provided, while dynamic does not. It determines the type only at runtime.
1 // var has determined the type in the compilation phase. 2 // var varError; 3 var isIntType = 3; 4 isIntType. toString (); 5 // dynamic does not perform any 6 // type check during compilation, but puts the type check to 7 // 8 dynamic dyn = 3 during runtime; 9 // dynamic dynOk; 10 dyn = "hello world"; 11 // The error string does not have the [fn nonexistent method] Method 12 // but it is passed during syntax check, syntax Error 13 var s = dyn. fn nonexistent method (); // runtime error
Because dynamic checks the type only at run time, sometimes an error occurs, so it must be used properly. When will it be more convenient to use it? We first define a Person class, and then use reflection to dynamically call the Talk method:
1 class Person2 {3 public void Talk(string msg)4 {5 MessageBox.Show(msg);6 }7 }
1 // dynamic can simplify Code 2 System during reflection. type t = typeof (Person); 3 var obj = Activator. createInstance (t, null); 4 t. invokeMember ("Talk", System. reflection. bindingFlags. invokeMethod, null, obj, new object [] {"hell world! "});
During reflection, method calls of traditional methods are often cumbersome, while dyanmic is simplified and intuitive:
1 dynamic obj2 = Activator.CreateInstance(t, null);2 obj2.Talk("hell world!");
Therefore, as long as dynamic uses the method, it is a very good feature of C.