Use dynamic to simplify reflection implementation, call a specified method or constructor, dynamic Constructor
Dynamic is a new feature of Framework4.0. The emergence of dynamic makes C # have the characteristics of a weak language type. during compilation, the compiler does not check the type and reports no error, however, if a non-existent attribute or method is executed during running, the running program throws a RuntimeBinderException.
Differences between var and dynamic
Var is the syntactic sugar provided by the compiler. During the compilation period, it matches the actual type and replaces the declaration of this variable.
After a dynamic is compiled, it is actually an object type, except that the compiler performs special processing on dynamic and places the type check during runtime.
From the compiler window of VS, we can see that the variables declared by var have smart prompts in VS, because VS can infer the actual type, and the variables declared by dynamic have no smart prompts.
Use dynamic to simplify reflection
public class DynamicSample { public string Name { get; set; } public int Add(int a, int b) { return a + b; } }
Public partial class DynamicPage: System. web. UI. page {protected void Page_Load (object sender, EventArgs e) {// common reflection practices DynamicSample dynamicSample = new DynamicSample (); var addMethod = typeof (DynamicSample ). getMethod ("Add"); int res = (int) addMethod. invoke (dynamicSample, new object [] {1, 2}); // The dynamic method is concise. dynamic dynamicSample2 = new DynamicSample () is recommended; int res2 = dynamicSample2.Add (1, 2); // Add will not be intelligently prompted }}
Another advantage of using dynamic is that the reflection performance is better than that without optimization, which is equivalent to the optimized reflection performance, but the code is clean and high. The author also pasted the code and pasted the running result, I have not made many introductions, so I will do it here.